Jquery .animate() stop scrolling when user scrolls manually?

前端 未结 4 521
半阙折子戏
半阙折子戏 2020-12-04 14:21

I have set up a snippet that scrolls a page section into view when it\'s clicked, the problem is that if the user wants to scroll in the middle of the animation the scroll k

相关标签:
4条回答
  • 2020-12-04 14:48

    Change your function to this:

    var page = $("html, body");
    
    $( "section" ).click(function(e) {
    
       page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
           page.stop();
       });
    
       page.animate({ scrollTop: $(this).position().top }, 'slow', function(){
           page.off("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove");
       });
    
       return false; 
    });
    

    This will:

    • Stop the animation if the user scrolls manually (only during the animation)
    • Does not obstruct your normal jQuery animation, such some of the other answers would

    Some extra information:

    Why are you binding to all of those events? "scroll mousewheel etc..."

    There are many different types of scroll events. You can scroll down using your mouse, keyboard, touchscreen, etc. With this we make sure to catch all of them.

    What is the use of var page = $("html, body");? Can't I just use $("html, body") everywhere?

    If you use the same selector more than once, it's good practice to cache them in a variable. It will be easier to write/use, and has better performance than having the program re-calculate the selector every time.

    Where can I find more info on .animate() and .stop()?

    You can read the jQuery documentation for .animate() and .stop(). I also recommend reading about animation queue's since .stop() works on this principle.

    0 讨论(0)
  • 2020-12-04 14:50
    $("your selector").scroll(function(){
     $('html,body').stop();
    });
    

    reference stop

    0 讨论(0)
  • 2020-12-04 14:51

    Try this

    $('html,body').scroll(function() {
        $(this).stop(true, false);
    });
    

    It will also remove all other animations from the element's queue, but it won't "jump" to the end of the current scroll animation.

    0 讨论(0)
  • 2020-12-04 15:08

    I would do it by detecting user events

    $('body,html').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove', function (e) {
      if (e.which > 0 || e.type == "mousedown" || e.type == "mousewheel" || e.type == "touchmove") {
        $("html,body").stop();
      }
    });
    

    Here is a good tutorial.

    0 讨论(0)
提交回复
热议问题