Javascript 让用户滚动停止scrolltop的jquery动画?

Javascript 让用户滚动停止scrolltop的jquery动画?,javascript,jquery,Javascript,Jquery,我想让网页自动滚动到某个元素,但我不希望滚动与用户输入冲突——如果它开始滚动,然后用户滚动,我希望自动滚动停止,让用户完全控制 所以我原本以为我可以做这样的事情: var animatable = $('body, html'); animatable.animate({scrollTop: $('#foo').offset()}, 1000); $(window).scroll(function() { animatable.stop(); }); 然而,问题是——scrollTop的动画

我想让网页自动滚动到某个元素,但我不希望滚动与用户输入冲突——如果它开始滚动,然后用户滚动,我希望自动滚动停止,让用户完全控制

所以我原本以为我可以做这样的事情:

var animatable = $('body, html');
animatable.animate({scrollTop: $('#foo').offset()}, 1000);

$(window).scroll(function() { animatable.stop(); });
然而,问题是——scrollTop的动画会触发window的滚动事件处理程序!因此,动画开始,然后立即停止


我正在寻找一种方法,我可以使我的窗口滚动事件处理程序只停止,如果它是由用户输入触发。。。这可能吗?

二极管的解决方案对我不起作用-scroll()没有区分动画和用户,这意味着动画立即停止。从a开始,以下内容适用于我(为此目的进行了修改):


这很有魅力。感谢您回答此问题。对于触摸屏设备,您需要将
touchstart
添加到事件列表中,并在事件本身
中检查它e、 类型=='touchstart'
@Benjammin'-好提示,小挑剔-使用
==
而不是
==
@OhadSchneider是的,隐式转换会咬你的屁股,但我不认为这种情况真的有任何假阳性的风险。但是是的,继续使用三重相等,这样可能更好。
// Assign the HTML, Body as a variable...
var $viewport = $('html, body');

// Some event to trigger the scroll animation (with a nice ease - requires easing plugin )...
$('#element').click(function() {
    $viewport.animate({ 
        scrollTop: scrollTarget // set scrollTarget to your desired position
    }, 1700, "easeOutQuint");
});

// Stop the animation if the user scrolls. Defaults on .stop() should be fine
$viewport.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e){
    if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
         $viewport.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup'); // This identifies the scroll as a user action, stops the animation, then unbinds the event straight after (optional)
    }
});