我正在编写一个无限滚动函数,并且如果$(window).scrollTop()
几乎和文档高度一样大,那么它就会运行,并且它运行得很好......
问题是新帖子加载需要几秒钟,在这段时间内,如果页面滚动,则在文档变大之前多次调用该函数,因此没有加载帖子的方式我打算。
我可以在函数中添加一行来暂停特定事件(在这种情况下是scroll
事件),直到函数执行完毕吗?
function f(){
//stop $(window).scroll
//execute code
//allow $(window).scroll
}
$(window).scroll(function(){
if(condition){
f();
}
});
答案 0 :(得分:1)
John Resig前一段时间发表了一篇文章
以下是他使用的代码
didScroll = false;
$(window).scroll(function() {
didScroll = true;
});
setInterval(function() {
if ( didScroll ) {
didScroll = false;
// Check your page position and then
// Load in more results
}
}, 250);
答案 1 :(得分:0)
您可以使用$.off
取消绑定某个事件,但我建议您只使用一个变量来跟踪它是否已被触发。
此代码段将阻止在scrolling
再次设置为false之前调用f。
$(window).scroll(function(){
if(this.scrolling == undefined)
this.scrolling = false;
if(this.scrolling == false){
this.scrolling = true;
f();
}
});
function f(){
//execute code
window.scrolling = false;
}
答案 2 :(得分:0)
您可以在调用后删除滚动事件,然后在/当加载帖请求完成时重新附加:
function loadPosts() {
if (condition) { // e.g. scrollTop almost equal to document height.
$(window).off('scroll', loadPosts);
$('[selector]').load('[URL-to-posts]', function(posts) {
bindScroll();
// Display posts.
});
}
}
// Binds the scroll event.
function bindScroll() {
$(window).on('scroll', loadPosts);
}
$(bindScroll); // Call on document ready.