javascript 让用户滚动停止 scrolltop 的 jquery 动画?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8858994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
let user scrolling stop jquery animation of scrolltop?
提问by patrick
I want to make it so that a webpage automatically scrolls to a certain element, however I don't want the scrolling to fight user input-- If it begins to scroll and then the user scrolls, I want the automated scrolling to stop and let the user have full control.
我想让网页自动滚动到某个元素,但是我不希望滚动对抗用户输入——如果它开始滚动然后用户滚动,我希望自动滚动停止并让用户拥有完全控制权。
So I originally thought I could do something like this:
所以我最初认为我可以做这样的事情:
var animatable = $('body, html');
animatable.animate({scrollTop: $('#foo').offset()}, 1000);
$(window).scroll(function() { animatable.stop(); });
however, the problem is-- the animation of the scrollTop triggers the scroll event handler for window! So, the animation begins and then stops immediately.
然而,问题是——scrollTop 的动画触发了窗口的滚动事件处理程序!因此,动画开始然后立即停止。
I am looking for a way that I can make my window scroll event handler only stop if it's triggered by user input... Is this possible?
我正在寻找一种方法,可以让我的窗口滚动事件处理程序仅在用户输入触发时停止......这可能吗?
回答by Tom Bates
Diode's solution didn't work for me - scroll() didn't differentiate between the animation and the user, meaning the animation stopped immediately. From a different post, the following works for me (modified for this purpose):
Diode 的解决方案对我不起作用 - scroll() 没有区分动画和用户,这意味着动画立即停止。来自不同的帖子,以下内容对我有用(为此目的修改):
// 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)
}
});