简体   繁体   中英

Jquery scroll to top of each section with button press not working

Im trying to animate the scroll to each section on button press. I have done lots of research and came across with this:

$('ul.nav').find('a').click(function () {
    var $href = $(this).attr('href');
     var $anchor = $('#' + $href).offset();
     $('body').animate({scrollTop: $anchor.top});
     return false;
 });

But it's not working. It just scroll without the animation. Can somebody help me please?

My HTML code:

<nav id="nav">
    <ul>
        <li class="current"><a href="index.php">Hlavní stránka</a></li>
        <li><a href="#rooms">Naše pokoje</a></li>
        <li><a href="#prizes">Ceník</a></li>
        <li><a href="#footer">Kontakt</a></li>
    </ul>
</nav>

You just used a wrong selector...

Try with this:

$('#nav ul li a').click(function(e) {

    // Get the href
    var $href = $(this).attr('href');

    // Animate only if the href contains the # character.
    if($href.substr(0,1) == "#"){}
      e.preventDefault();

      // Here, the # sign is already present.
      var $anchor = $($href).offset();
      $('body').animate({scrollTop: $anchor.top},1000);  // Set a delay here, in milliseconds.
    }
});

And I would use preventDefault() instead of return false;

EDITED to care about the first anchor which looks like to be a "real" link to trigger a page load.

You are looking for

$('#nav ul li a').click(function () {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

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