让用户滚动停止jtopery scrolltop的动画?

时间:2012-01-14 00:20:22

标签: javascript jquery

我想这样做,以便网页自动滚动到某个元素,但我不希望滚动对抗用户输入 - 如果它开始滚动然后用户滚动,我想自动滚动到停止并让用户完全控制。

所以我原本以为我可以这样做:

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

$(window).scroll(function() { animatable.stop(); });

然而,问题是 - scrollTop的动画触发窗口的滚动事件处理程序!因此,动画开始然后立即停止。

我正在寻找一种方法,只有在用户输入触发时才能使窗口滚动事件处理程序停止...这可能吗?

1 个答案:

答案 0 :(得分:56)

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

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