仅在用户滚动时调用Scroll,而不在animate()时调用 [英] Call Scroll only when user scrolls, not when animate()

查看:181
本文介绍了仅在用户滚动时调用Scroll,而不在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;
})

此代码是有问题的,因为animate()算作滚动,因此在停止自身之前只移动了一点点.

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.

用户滚动时是否可以调用我的滚动功能,而不是animate()?

Is there any way to call my scroll function when the user scrolls, not the animate()?

推荐答案

您可以编写自己的代码来设置动画值,并设置一个标志来指示更改来自动画.

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

例如:(未经测试)

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;
})

您可以为scrollLeft做同样的事情.

You can do the same thing for scrollLeft.

请注意,我假设设置scrollTop是可重入的调用,因此在E.elem.scrollTop = E.now行中触发了scroll事件.如果它不是可重入的(可能仅在某些浏览器中),则在scrollAnimating设置回false之后将触发该事件.要解决此问题,您可以在scroll事件中重置scrollAnimating.

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.

这篇关于仅在用户滚动时调用Scroll,而不在animate()时调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆