问题描述
当用户单击指向同一页面的链接时,我的网页会为滚动动画。我想在用户尝试滚动时立即取消此动画(否则,用户和浏览器将争夺控制权)–无论是使用鼠标滚轮,键盘还是滚动条(或任何其他方式),是否还有其他方式滚动?)。使用鼠标滚轮或键盘后,我设法取消了动画,如何使它与滚动条一起使用?
这是我的代码查找键盘的方式:
$(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,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,0.0);
}
x=$(\"html,body\").prop(\'animatedMark\');
return x;
};
//Kills the animation
function stopBodyAnimation() {
lastAnimatedMark=0;
$(\"html,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,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,false);
}
}