所以我目前使用的是:
$(window).resize(function(){resizedw();});
但是在调整大小过程中,这个函数会被调用很多次。是否有可能在事件结束时捕获事件?
所以我目前使用的是:
$(window).resize(function(){resizedw();});
但是在调整大小过程中,这个函数会被调用很多次。是否有可能在事件结束时捕获事件?
当前回答
有一个优雅的解决方案使用下划线。js所以,如果你在你的项目中使用它,你可以做以下-
$( window ).resize( _.debounce( resizedw, 500 ) );
这应该足够了:)但是,如果你有兴趣阅读更多,你可以查看我的博客文章- http://rifatnabi.com/post/detect-end-of-jquery-resize-event-using-underscore-debounce(deadlink)
其他回答
有一个优雅的解决方案使用下划线。js所以,如果你在你的项目中使用它,你可以做以下-
$( window ).resize( _.debounce( resizedw, 500 ) );
这应该足够了:)但是,如果你有兴趣阅读更多,你可以查看我的博客文章- http://rifatnabi.com/post/detect-end-of-jquery-resize-event-using-underscore-debounce(deadlink)
我很幸运地推荐了以下网站:http://forum.jquery.com/topic/the-resizeend-event
下面是代码,这样你就不必去挖掘他的帖子的链接和源代码:
var rtime;
var timeout = false;
var delta = 200;
$(window).resize(function() {
rtime = new Date();
if (timeout === false) {
timeout = true;
setTimeout(resizeend, delta);
}
});
function resizeend() {
if (new Date() - rtime < delta) {
setTimeout(resizeend, delta);
} else {
timeout = false;
alert('Done resizing');
}
}
谢谢森那美。Vidas for code!
您可以将引用id存储到任何setInterval或setTimeout。是这样的:
var loop = setInterval(func, 30);
// some time later clear the interval
clearInterval(loop);
要在不使用“全局”变量的情况下做到这一点,可以向函数本身添加一个局部变量。例:
$(window).resize(function() {
clearTimeout(this.id);
this.id = setTimeout(doneResizing, 500);
});
function doneResizing(){
$("body").append("<br/>done!");
}
Mark Coleman的答案当然比所选的答案要好得多,但如果你想避免超时ID的全局变量(Mark回答中的doit变量),你可以做以下其中之一:
(1)使用立即调用的函数表达式(IIFE)来创建闭包。
$(window).resize((function() { // This function is immediately invoked
// and returns the closure function.
var timeoutId;
return function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
timeoutId = null; // You could leave this line out.
// Code to execute on resize goes here.
}, 100);
};
})());
(2)使用事件处理函数的属性。
$(window).resize(function() {
var thisFunction = arguments.callee;
clearTimeout(thisFunction.timeoutId);
thisFunction.timeoutId = setTimeout(function() {
thisFunction.timeoutId = null; // You could leave this line out.
// Code to execute on resize goes here.
}, 100);
});
你可以使用setTimeout()和clearTimeout()
function resizedw(){
// Haven't resized in 100ms!
}
var doit;
window.onresize = function(){
clearTimeout(doit);
doit = setTimeout(resizedw, 100);
};
jsfiddle上的代码示例。