当onresize事件被触发时,我在尝试只运行一次函数时遇到了一些问题,我已经查看了这个问题DOM onresize event,但我没有使用jQuery,并且无法在没有该函数的情况下运行该函数。有什么建议吗?
发布于 2012-06-22 05:57:31
在调整大小操作期间,对每个帧调用一次resize事件。如果你想在大小调整完成时调用它,只需使用回调函数设置计时器即可。
var timeOut = null;
window.onresize = function(){
if (timeOut != null)
clearTimeout(timeOut);
timeOut = setTimeout(function(){
// YOUR RESIZE CODE HERE
}, 500);
};发布于 2012-06-22 05:56:26
您可以使用debounce实现from underscore
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
if (immediate && !timeout) func.apply(context, args);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
window.onresize = debounce(function() {
// Your code here
}, 500);或者使用library from the linked question。没有jQuery,它就是Cowboy.debounce(...)。
https://stackoverflow.com/questions/11147266
复制相似问题