在浏览器窗口完成大小调整后,如何调用函数?
我试着这样做,但我遇到了问题。我使用的是JQuery Resize事件函数:
$(window).resize(function() {
... // how to call only once the browser has FINISHED resizing?
});
但是,如果用户手动调整浏览器窗口的大小,则会连续调用此函数。这意味着,它可能会在很短的时间间隔内调用此函数数十次。
我如何才能只调用一次resize函数(一旦浏览器窗口完成大小调整)?
更新
也不需要使用全局变量。
发布于 2010-11-29 03:42:21
Here is an example using thejh's instructions
您可以存储任何setInterval或setTimeout的引用id。如下所示:
var loop = setInterval(func, 30);
// some time later clear the interval
clearInterval(loop);
发布于 2010-11-29 03:46:16
function debouncer( func , timeout ) {
var timeoutID , timeout = timeout || 200;
return function () {
var scope = this , args = arguments;
clearTimeout( timeoutID );
timeoutID = setTimeout( function () {
func.apply( scope , Array.prototype.slice.call( args ) );
} , timeout );
}
}
$( window ).resize( debouncer( function ( e ) {
// do stuff
} ) );
注意,你可以使用这个方法来处理任何你想要去掉的东西(按键事件等)。
调整超时参数以获得所需的最佳效果。
发布于 2013-03-02 10:42:56
您可以将setTimeout()
和clearTimeout()
与jQuery.data
结合使用
$(window).resize(function() {
clearTimeout($.data(this, 'resizeTimer'));
$.data(this, 'resizeTimer', setTimeout(function() {
//do something
alert("Haven't resized in 200ms!");
}, 200));
});
更新
我编写了一个扩展来增强jQuery的默认事件处理程序(& bind
)- on
-handler。如果事件在给定时间间隔内未被触发,它会将一个或多个事件的事件处理函数附加到所选元素。如果只想在延迟后触发回调,这很有用,比如resize事件。https://github.com/yckart/jquery.unevent.js
;(function ($) {
var methods = { on: $.fn.on, bind: $.fn.bind };
$.each(methods, function(k){
$.fn[k] = function () {
var args = [].slice.call(arguments),
delay = args.pop(),
fn = args.pop(),
timer;
args.push(function () {
var self = this,
arg = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
fn.apply(self, [].slice.call(arg));
}, delay);
});
return methods[k].apply(this, isNaN(delay) ? arguments : args);
};
});
}(jQuery));
可以像使用任何其他on
或bind
-event处理程序一样使用它,只是您可以将额外的参数作为最后一个参数进行传递:
$(window).on('resize', function(e) {
console.log(e.type + '-event was 200ms not triggered');
}, 200);
https://stackoverflow.com/questions/4298612
复制相似问题