Call Scroll only when user scrolls, not when animate()

后端 未结 3 481
清酒与你
清酒与你 2020-12-03 16:32

I have a few links across the page with the purpose of \"going to the top\", accomplished by scrolling the page to the top with a nice animation. I\'ve noticed that sometime

3条回答
  •  無奈伤痛
    2020-12-03 16:58

    You could make write your own code to set the animation value, and set a flag indicating that the change comes from an animation.

    For example: (Untested)

    var scrollAnimating = false
    jQuery.fx.step.scrollTop = function(E) {
        scrollAnimating = true;
        E.elem.scrollTop = E.now;
        scrollAnimating = false;
    };
    
    $('#gototop').click(function() {
        $('body').animate({scrollTop:0},3000);
        $(window).scroll(function () {
            if (!scrollAnimating)
                $('body').stop();
        });
        return false;
    })
    

    You can do the same thing for scrollLeft.

    Note that I'm assuming that setting scrollTop is a reentrant call, so that the scroll event is fired inside the line E.elem.scrollTop = E.now. If it's not reentrant (it might be only in some browsers), the event will be fired after scrollAnimating gets set back to false. To fix that, you could reset scrollAnimating inside the scroll event.

提交回复
热议问题