我使用JQuery这样:
$(window).resize(function() { ... });
但是,如果用户通过拖动窗口边缘来手动调整浏览器窗口的大小,上面的.resize事件会触发多次。
问题:如何在浏览器窗口调整大小完成后调用函数(使事件只触发一次)?
我使用JQuery这样:
$(window).resize(function() { ... });
但是,如果用户通过拖动窗口边缘来手动调整浏览器窗口的大小,上面的.resize事件会触发多次。
问题:如何在浏览器窗口调整大小完成后调用函数(使事件只触发一次)?
当前回答
声明全局延迟侦听器:
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).bind('resize', function(e){
window.resizeEvt;
$(window).resize(function(){
clearTimeout(window.resizeEvt);
window.resizeEvt = setTimeout(function(){
//code to do after window is resized
}, 250);
});
});
许多解决方案。我尝试在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
});
假设鼠标光标在窗口调整大小后应该返回到文档,我们可以使用onmouseover事件创建一个类似回调的行为。不要忘记,这个解决方案可能不适用于预期的触摸屏。
var resizeTimer;
var resized = false;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
if(!resized) {
resized = true;
$(document).mouseover(function() {
resized = false;
// do something here
$(this).unbind("mouseover");
})
}
}, 500);
});
我喜欢创建一个事件:
$(window).bind('resizeEnd', function() {
//do something, window hasn't changed size in 500ms
});
下面是如何创建它:
$(window).resize(function() {
if(this.resizeTO) clearTimeout(this.resizeTO);
this.resizeTO = setTimeout(function() {
$(this).trigger('resizeEnd');
}, 500);
});
你可以把它放在某个全局javascript文件中。
如果你安装了Underscore.js,你可以:
$(window).resize(_.debounce(function(){
alert("Resized");
},500));