Javascript 检测用户是否正在滚动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10605197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect if user is scrolling
提问by user1365010
How can I detect in javascript if the user is scrolling?
如果用户正在滚动,我如何在 javascript 中检测?
回答by Wampie Driessen
this works:
这有效:
window.onscroll = function (e) {
// called when the window is scrolled.
}
edit:
编辑:
you said this is a function in a TimeInterval..
Try doing it like so:
你说这是一个 TimeInterval 中的函数..
尝试这样做:
userHasScrolled = false;
window.onscroll = function (e)
{
userHasScrolled = true;
}
then inside your Interval insert this:
然后在您的 Interval 中插入:
if(userHasScrolled)
{
//do your code here
userHasScrolled = false;
}
回答by Oscar Jara
You just said javascript in your tags, so @Wampie Driessen post could helps you.
您刚刚在标签中说了 javascript,所以@Wampie Driessen 的帖子可以帮助您。
I want also to contribute, so you can use the following when using jQuery if you need it.
我也想贡献一下,所以如果你需要的话,你可以在使用 jQuery 时使用以下内容。
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.wheelDelta< 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
Another example:
另一个例子:
$(function(){
var _top = $(window).scrollTop();
var _direction;
$(window).scroll(function(){
var _cur_top = $(window).scrollTop();
if(_top < _cur_top)
{
_direction = 'down';
}
else
{
_direction = 'up';
}
_top = _cur_top;
console.log(_direction);
});
});?
回答by Silas S. Brown
window.addEventListener("scroll",function(){
window.lastScrollTime = new Date().getTime()
});
function is_scrolling() {
return window.lastScrollTime && new Date().getTime() < window.lastScrollTime + 500
}
Change the 500 to the number of milliseconds after the last scroll event at which you consider the user to be "no longer scrolling".
将 500 更改为您认为用户“不再滚动”的最后一个滚动事件之后的毫秒数。
(addEventListener
is better than onScroll
because the former can coexist nicely with any other code that uses onScroll
.)
(addEventListener
比onScroll
因为前者可以与使用onScroll
.的任何其他代码很好地共存更好。)
回答by hitautodestruct
Use an interval to check
使用间隔检查
You can setup an interval to keep checking if the user has scrolled then do something accordingly.
您可以设置一个时间间隔来继续检查用户是否已滚动,然后相应地执行某些操作。
Borrowing from the great John Resigin his article.
借用了伟大的John Resig在他的文章中。
Example:
例子:
let didScroll = false;
window.onscroll = () => didScroll = true;
setInterval(() => {
if ( didScroll ) {
didScroll = false;
console.log('Someone scrolled me!')
}
}, 250);