简体   繁体   中英

jQuery: Anchor scrolling jumpy

I am using some code from www.css-tricks.com that can be used to animate local scrolling to a page anchor. Here is the code snippet:

$("class-name-here").on("click", function() {
    var $target = $(this.hash);
    $target = $target.length && $target
    || $('[name=' + this.hash.slice(1) +']');
    if ($target.length) {
        var targetOffset = $target.offset().top;
        $('html,body')
        .animate({scrollTop: targetOffset}, 1500, "easeOutQuint");
     return false;
    }
});

I have tried using a variety of times for the animation duration, but when I click the link, the page does scroll correctly, but after the scroll reaches the destination, the animation continues. In other words, it scrolls, but after the animation seems complete, if you try to scroll away manually, the page animates itself to that location again for about half a second.

Is there something wrong with the snippet / has anyone seen this before?

I found an example where we stop the scroll-event on different kind of events. I made an example for you without using jquery-ui. The scroll-timer is set to 2.5 sec so that you can stop it anytime before it reaches its target: JS-FIDDLE

function goTo(sectionID) {

   var page = $("html, body");
   page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
       page.stop();
   });

   page.animate({ scrollTop: $("#section" + sectionID).offset().top }, 2500, 'swing', function(){
       page.off("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove");
   });

   return false; 
};

Can you try this :

$('.your-class-name-here').click(function(event) {
        var id = $(this).attr("href");
        var offset = 10;
        var target = $(id).offset().top - offset;
        $('html, body').animate({scrollTop:target}, 1000);
        event.preventDefault();
    });       

});

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