除非用户开始滚动,否则javascript会自动滚动到顶部

时间:2013-07-19 11:51:51

标签: javascript jquery scroll

我想自动滚动到顶部,但如果用户开始滚动则会挽救。

我目前所拥有的内容会过早停止动画,因为滚动动画本身就是滚动 - 所以它会触发“滚动发生时停止滚动”动作。

function stop_scrolling_to_top(){
    // stop animation attached to selector
    $('html, body').stop();
}

// scroll to the top automatically
$('html, body').animate({ scrollTop: 0}, 1400, "easeOutQuint", function(){ 
    // callback when animation complete
    do_not_do_when_scrolling(stop_scrolling_to_top);
});

// stop animation if scrolling starts
do_when_scrolling(stop_scrolling_to_top);

有没有办法确定滚动是由人还是js触发?完全有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

希望这会有所帮助。

它会侦听鼠标滚轮事件+可用于在页面上滚动的键(向上/向下翻页,空格键,箭头键等):

$(document).keyup(function(e){

    if($.inArray(e.which, [33,34,32,38,40]) !== -1)
        console.log('key');
        //potential scroll by key

});

$(document).bind((/Firefox/i.test(navigator.userAgent)) 
                                 ? 'DOMMouseScroll' 
                                 : 'mousewheel', function(e){

    var evt = window.event || e;   
    evt = evt.originalEvent ? evt.originalEvent : evt;               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta;

    if(delta > 0) 
        console.log('mousewheel up');
        //scroll up
    else
        console.log('mousewheel down');
        //scroll down  
});

如果您注意到“您的”滚动有效,请像上面那样停止:

if($('html, body').is(':animated'))
    $('html, body').stop();

http://jsfiddle.net/MQQ3F/1/

答案 1 :(得分:-1)

为什么不简单地听一下mousewheel事件。如果它被解雇,用户试图自己滚动。如果用户点击某处停止滚动,你也可以听一下点击事件......

相关问题