我正在使用以下代码找出查看者正在访问页面的哪一部分(类似于 google books,找出正在查看的页面):
$("#main-content").scroll(function () {
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select(undefined);
});
同样在另一部分中,我使用 $(window).resize( ... )
使我的内容适合当前窗口大小,每次调整大小都会调用它。正如您可以想象的那样,这会大大降低页面速度,特别是在较旧的硬件上。有没有什么方法可以意识到何时停止滚动或调整大小然后开始做这些事情,从而减少进程数?类似于 $("#main-content").scrollStop
???
最佳答案
你可以做两件事。
1.) 设置超时,以便调整大小/滚动仅在某个空闲状态后发生:
var timeout;
$("#main-content").scroll(function () {
clearTimeout(timeout);
timeout = setTimeout(function(){
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select(); // note: undefined is passed by default
}, 200);
});
2.)限制调用次数/秒:
var lastScroll = 0;
$("#main-content").scroll(function () {
var now = +new Date;
if (now - lastScroll > 100) { // only execute if (elapsed > 100ms)
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select();
lastScroll = now;
}
});
关于javascript - 减少 .resize 和 .scroll 方法的调用次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4420853/