我使用JQuery这样:
$(window).resize(function() { ... });
但是,如果用户通过拖动窗口边缘来手动调整浏览器窗口的大小,上面的.resize事件会触发多次。
问题:如何在浏览器窗口调整大小完成后调用函数(使事件只触发一次)?
我使用JQuery这样:
$(window).resize(function() { ... });
但是,如果用户通过拖动窗口边缘来手动调整浏览器窗口的大小,上面的.resize事件会触发多次。
问题:如何在浏览器窗口调整大小完成后调用函数(使事件只触发一次)?
当前回答
这是我实现的:
$(window).resize(function(){ setTimeout(someFunction, 500); });
如果我们期望resize发生的时间小于500ms,我们可以清除setTimeout
祝你好运…
其他回答
这对我很管用。 请参阅此解决方案- https://alvarotrigo.com/blog/firing-resize-event-only-once-when-resizing-is-finished/
var resizeId; $(窗口).resize(函数(){ clearTimeout (resizeId); resizeId = setTimeout(doneResizing, 500); }); 函数doneResizing () { //我们想做的任何事情 }
声明全局延迟侦听器:
var resize_timeout;
$(window).on('resize orientationchange', function(){
clearTimeout(resize_timeout);
resize_timeout = setTimeout(function(){
$(window).trigger('resized');
}, 250);
});
下面使用监听器来调整事件大小:
$(window).on('resized', function(){
console.log('resized');
});
这是我实现的:
$(window).resize(function(){ setTimeout(someFunction, 500); });
如果我们期望resize发生的时间小于500ms,我们可以清除setTimeout
祝你好运…
许多解决方案。我尝试在mouuseevent之后执行事件,所以我在ouse进入窗口后添加了重载:
jQuery(window).resize(function() {
// this. is window
if( this.resizeTO) {
clearTimeout(this.resizeTO)
};
this.resizeTO = setTimeout(function() {
jQuery(window).mouseenter(function() {
if( jQuery(window).width() < 700 && jQuery(window).width() > 400 ){
console.log("mouseenter reloads elements");
// is loading the page
location.reload();
//
}; // just mobile
}); // mouse fired
}, 400); // set Time Ouuut
});
非常感谢大卫沃尔什,这里是一个香草版本的下划线debounce。
代码:
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
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);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
简单的用法:
var myEfficientFn = debounce(function() {
// All the taxing stuff you do
}, 250);
$(window).on('resize', myEfficientFn);
裁判:http://davidwalsh.name/javascript-debounce-function