我需要检查一下html页面是否在窗口顶部。
所以,我正在使用这段代码:
$(window).scroll(function(){
a = ($(window).scrollTop());
if (a>0) {
alert('page not in top');
}
});
但是这没有按预期工作,因为只有当用户停止滚动操作时才会触发事件。有什么想法吗?
答案 0 :(得分:1)
使用setTimeout
:
var timeout;
$(window).scroll(function() {
clearTimeout(timeout);
timeout = setTimeout(function(){
a = $(window).scrollTop();
if ( a > 0 ) {
alert('page not in top');
}
}, 100);
});
答案 1 :(得分:1)
试试这个:
var timer = null;
$(window).addEventListener('scroll', function() {
if(timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(function() {
// do something
}, 150);
}, false);
或者这个:
var timer;
$(window).bind('scroll',function () {
clearTimeout(timer);
timer = setTimeout( refresh , 150 );
});
var refresh = function () {
// do stuff
console.log('Stopped Scrolling');
};