Eva*_*ler 2 javascript jquery scroll
我有一些jQuery代码来检查我是否滚动到窗口的底部.
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() == $(document).height()) {
appendToGrid();
}
})
Run Code Online (Sandbox Code Playgroud)
我的appendToGrid()函数将用户滚动到页面顶部并添加内容.问题是,我需要每个滚动调用一次这个函数.就像我现在一样,它每次滚动被调用多次.
如果我改成它
$(window).one('scroll',function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
appendToGrid();
}
});
Run Code Online (Sandbox Code Playgroud)
它只会触发一次,但我需要它每次滚动一次,所以用户可以滚动到底部并继续发送回页面顶部.
我也尝试过以下但它仍然会多次发射.
var fired = false;
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() == $(document).height() && !fired) {
fired = true;
appendToGrid();
fired = false;
}
})
Run Code Online (Sandbox Code Playgroud)
一旦调用appendToGrid,您可以添加冷却计时器.这类似于你的fired旗帜,但它只在等待2000ms后重置.您可以将时间调整到最佳状态.
var recentScroll = false;
$(window).on('scroll',function() {
if(!recentScroll && $(window).scrollTop() + $(window).height() == $(document).height()) {
appendToGrid();
recentScroll = true;
window.setTimeout(() => { recentScroll = false; }, 2000)
}
});
Run Code Online (Sandbox Code Playgroud)
另一种选择是限制逻辑,使其仅在用户停止操作一段时间后才会发生。
$(function(){
//cache common variables so they are created once
var $window = $(window);
var $document = $(document);
var debounce;
$window.on('scroll', function(){
//clear the delay if it's not finished yet
if (debounce) clearTimeout(debounce);
//start a new delay
debounce = setTimeout(function(){
//remove reference so another delay can start
debounce = null;
//perform whatever logic you normally would do
if($window.scrollTop() + $window.height() == $document.height()) {
appendToGrid();
}
}, 300);
});
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2089 次 |
| 最近记录: |