让用户滚动停止jtopery scrolltop的动画? [英] let user scrolling stop jquery animation of scrolltop?

查看:270
本文介绍了让用户滚动停止jtopery scrolltop的动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

however, the problem is-- the animation of the scrollTop triggers the scroll event handler for window! So, the animation begins and then stops immediately.

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

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?

推荐答案

二极管的解决方案对我不起作用 - scroll()没有区分动画和用户,意味着动画立即停止。来自不同帖子,以下适用于我(为此目的而修改):

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):

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

这篇关于让用户滚动停止jtopery scrolltop的动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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