用户交互后取消滚动 [英] Cancel scrolling after user interaction
问题描述
当用户点击指向同一页面的链接时,我的网页会动画滚动。我想在用户尝试滚动时取消此动画(否则用户和浏览器正在争夺控制权) - 无论是使用鼠标滚轮,键盘还是滚动条(或任何其他方式 - 还有其他方式滚动?)。在使用鼠标滚轮或键盘后我设法取消动画,如何使用滚动条?
My webpage animates scrolling when users click on links to the same page. I want to cancel this animation as soon as the user tries to scroll (otherwise the user and the browser are fighting for control) – no matter whether with the mouse wheel, the keyboard or the scrollbar (or any other way – are there other ways of scrolling?). I managed to cancel the animation after the mouse wheel or keyboard are used, how do I get this working with the scrollbar?
以下是我的代码查找键盘的方式:
Here is how my code looks for the keyboard:
$(document.documentElement).keydown( function (event) {
if(event.keyCode == 38 || 40) stopScroll();
});
function stopScroll() {
$("html, body").stop(true, false);
}
我还尝试使用<$ c $更优雅的方式c> scroll(),问题是 scroll()
捕获包括动画和自动滚动在内的所有内容。除了动画滚动之外,我想不出有什么方法可以让它捕捉所有滚动。
I also tried a more elegant way of doing this by using scroll()
, the problem is that scroll()
catches everything including the animated and automated scrolling. I could not think of any way to let it catch all scrolling except the animated scrolling.
推荐答案
你需要动画标记,类似于这个
you need animation marker, something like this
$("html, body").stop(true, false).prop('animatedMark',0.0).animate({scrollTop : top, animatedMark: '+=1.0'})
这是代码,代码是GWT和javascript的混合所以把它移到js,没有经过全面测试,请试试吧
Here is the code, the code was mix of GWT and javascript so moved it to js, not fully tested, please try it
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/ #!取消-jquery-animation-after-user-interaction
享受!
这篇关于用户交互后取消滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!