简体   繁体   中英

scroll to the top jquery

im trying to create a simple "scroll jump to target". i have made the parts which it jumps to everywhere except the "scroll to top". the jump works on id of the tag so it jumps to everywhere fine but since i have my nav bar position fixed, it wont jump to the top. here is my code to make it simpler to understand:

<ul class="nav navbar-nav">
    <li class="active"><a id="home" href="#home">Home<span class="sr-only">(current)</span></a></li>
    <li><a href="#services">Services</a></li>
    <li><a href="#about">About Us</a></li>
    <li><a href="#contacts">Contacts</a></li>
</ul>

further down:

<div id="wall_1" class="myImage" data-stellar-background-ratio="0.4" ></div>
    <div id="content_1" class="myContent">
        <div id="services"></div>
        ...
        <p><a href="#Home">Go to the top</a></p>
    </div>
    <div id="wall_2" class="myImage" data-stellar-background-ratio="0.4"  ></div>
    <div id="content_2" class="myContent" >
        <div id="about"></div>
        ...
        <p><a href="#Home">Go to the top</a></p>
    </div>
    <div id="wall_3" class="myImage" data-stellar-background-ratio="0.4"  ></div>
    <div id="content_2" class="myContent">
        <div id="contacts"></div>
        ...
        <p><a href="#Home">Go to the top</a></p>
</div>

JS:

<script>
    $(document).ready(function () {
        $('a[href^="#"]').on('click', function (e) {
            e.preventDefault();
            var target = this.hash;
            var $target = $(target);
            $('html, body').stop().animate({
                'scrollTop': $target.offset().top - 81
            }, 800, 'swing', function () {
                window.location.hash = target;
               });
        });
    });
</script>

how can i jump to the top (scroll to 0) now?

This should work:

$('html, body').stop().animate({
                    'scrollTop': 0
                }, 800, 'swing');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM