lis*_*aro 42 javascript css jquery
我已经设置了一个片段,当它被点击时将页面部分滚动到视图中,问题是如果用户想要在动画中间滚动滚动有点断断续续.
$( "section" ).click(function(e) {
$('html,body').animate({ scrollTop: $(this).position().top }, 'slow');
return false;
});
Run Code Online (Sandbox Code Playgroud)
如果用户手动滚动,如何停止jquery动画?
Pra*_*lin 118
将您的功能更改为:
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;
});
Run Code Online (Sandbox Code Playgroud)
这将:
一些额外的信息:
你为什么要约束所有这些事件?"滚动鼠标滚轮......"
有许多不同类型的滚动事件.您可以使用鼠标,键盘,触摸屏等向下滚动.有了这个,我们一定要抓住所有这些.
有什么用
var page = $("html, body");
?我不能$("html, body")
随处使用吗?
如果多次使用同一个选择器,最好将它们缓存在变量中.写入/使用会更容易,并且比每次程序重新计算选择器具有更好的性能.
我在哪里可以找到更多信息
.animate()
和.stop()
?
您可以阅读.animate()和.stop()的jQuery文档.我也建议阅读有关动画队列的信息,因为.stop()
这是基于这个原则.
我会通过检测用户事件来做到这一点
$('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();
}
});
Run Code Online (Sandbox Code Playgroud)
这是一个很好的教程。