用户交互后取消滚动

当用户点击指向同一页面的链接时,我的网页会动画滚动。 我想在用户尝试滚动时取消此动画(否则用户和浏览器正在争夺控制权) – 无论是使用鼠标滚轮,键盘还是滚动条(或任何其他方式 – 还有其他方式滚动?)。 我设法在使用鼠标滚轮或键盘后取消动画,如何使用滚动条?

以下是我的代码查找键盘的方式:

$(document.documentElement).keydown( function (event) { if(event.keyCode == 38 || 40) stopScroll(); }); function stopScroll() { $("html, body").stop(true, false); } 

我还尝试使用scroll()更优雅的方式,问题是scroll()捕获包括动画和自动滚动在内的所有内容。 除了动画滚动之外,我想不出任何让它能够捕获所有滚动的方法。

你需要动画标记,就像这样

 $("html, body").stop(true, false).prop('animatedMark',0.0).animate({scrollTop : top, animatedMark: '+=1.0'}) 

这是代码,代码是GWT和javascript的混合,所以把它移到js,没有经过全面测试,请尝试一下

 var lastAnimatedMark=0.0; function scrollToThis(top){ // Select/ stop any previous animation / reset the mark to 0 // and finally animate the scroll and the mark $("html, body").stop(true, false).prop('animatedMark',0.0). animate({scrollTop : top, animatedMark: '+=1.0'} ,10000,function(){ //We finished , nothing just clear the data lastAnimatedMark=0.0; $("html, body").prop('animatedMark',0.0); }); } //Gets the animatedMark value function animatedMark() { var x=$("html, body").prop('animatedMark'); if (x==undefined){ $("html, body").prop('animatedMark', 0.0); } x=$("html, body").prop('animatedMark'); return x; }; //Kills the animation function stopBodyAnimation() { lastAnimatedMark=0; $("html, body").stop(true, false); } //This should be hooked to window scroll event function scrolled(){ //get current mark var currentAnimatedMark=animatedMark(); //mark must be more than zero (jQuery animation is on) & but //because last=current , this is user interaction. if (currentAnimatedMark>0 && (lastAnimatedMark==currentAnimatedMark)) { //During Animation but the marks are the same ! stopBodyAnimation(); return; } lastAnimatedMark=currentAnimatedMark; } 

这是关于它的博客

http://alaamurad.com/blog/#!canceling-jquery-animation-after-user-interaction

请享用!

这是一个jquery函数,应该可以解决这个问题:

 function polite_scroll_to(val, duration, callback) { /* scrolls body to a value, without fighting the user if they try to scroll in the middle of the animation. */ var auto_scroll = false; function stop_scroll() { if (!auto_scroll) { $("html, body").stop(true, false); } }; $(window).on('scroll', stop_scroll); $("html, body").animate({ scrollTop: val }, { duration: duration, step: function() { auto_scroll = true; $(window).one('scroll', function() { auto_scroll = false; }); }, complete: function() { callback && callback(); }, always: function() { $(window).off('scroll', stop_scroll); } }); }; 

它不是很优雅,但您可以使用某种标志来检测您正在处理的滚动类型(动画或“手动”),并在动画时始终将其删除。 这是一个未经测试的例子:

 var animatedScroll = false; // you probably have a method looking something like this: function animatedScrollTo(top) { // set flag to true animatedScroll = true; $('html').animate({ scrollTop : top }, 'slow', function() { // reset flag after animation is completed animatedScroll = false; }); } function stopScroll() { if (animatedScroll) { $("html, body").stop(true, false); } }