仅在用户滚动时调用 Scroll,而不是在 animate() 时调用
我在页面上有一些链接,其目的是“转到顶部”,通过使用漂亮的动画将页面滚动到顶部来完成。我注意到,有时当页面滚动时,用户会想要向下滚动,但这是不可能的。屏幕只会卡顿,但会继续动画,直到到达顶部。
如果用户尝试滚动,我想停止动画,因此我编写了以下代码:
$('#gototop').click(function() {
$('body').animate({scrollTop:0},3000);
$(window).scroll(function () {
$('body').stop();
});
return false;
})
这段代码是有问题的,因为 animate() 算作滚动,因此它在停止之前只移动了一点点。
我也尝试过按下按键作为选项,但鼠标滚动未注册为按键。
当 user 滚动时,有什么方法可以调用我的滚动函数,而不是 animate() 吗?
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 sometimes while the page is scrolling the user will want to scroll back down, for example, but this is not possible. The screen will only stutter but will continue animating until it reaches the top.
I want to stop the animation if the user attempts to scroll, therefore I wrote this code:
$('#gototop').click(function() {
$('body').animate({scrollTop:0},3000);
$(window).scroll(function () {
$('body').stop();
});
return false;
})
This code is problematic, because the animate() counts as scrolling, therefore it only moves a tiny bit before it stops itself.
I've also tried key-down as an option but mouse scrolling doesn't register as a key.
Is there any way to call my scroll function when the user scrolls, not the animate()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以编写自己的代码来设置动画值,并设置一个标志来指示更改来自动画。
例如:(未经测试)
您可以对
scrollLeft
执行相同的操作。请注意,我假设设置
scrollTop
是可重入调用,因此scroll
事件在行E.elem.scrollTop = E.now 内触发
。如果它不可重入(可能仅在某些浏览器中),则在将scrollAnimating
设置回false
后将触发该事件。要解决此问题,您可以在scroll
事件中重置scrollAnimating
。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)
You can do the same thing for
scrollLeft
.Note that I'm assuming that setting
scrollTop
is a reentrant call, so that thescroll
event is fired inside the lineE.elem.scrollTop = E.now
. If it's not reentrant (it might be only in some browsers), the event will be fired afterscrollAnimating
gets set back tofalse
. To fix that, you could resetscrollAnimating
inside thescroll
event.我遇到了同样的问题,但我在 jQuery 文档上找到了解决方案。 animate 方法中有一个属性,可让您在动画完成时设置回调函数。
http://api.jquery.com/animate/#animate-属性-持续时间-缓动-完成
这是代码:
I was with the same problem, but I found a solution right on jQuery Documentation. There is a property in animate method that lets you set a callback function when animation is completed.
http://api.jquery.com/animate/#animate-properties-duration-easing-complete
Here is the code:
想通了!在互联网上查找后,我发现 Mozilla 的名为
Document.addEventListener
的东西和 IE 和 Opera 的document.onmousewheel
的东西可以捕获滚动事件。Figured it out! After looking around on the Internet I found something called
Document.addEventListener
for Mozilla anddocument.onmousewheel
for IE and Opera that will catch scrolling events.