[英]window.onresize fires twice
I'm new to js. 我是js的新手。 Please, don't kick painfully.
拜托,不要痛苦地踢。 I have this code
我有这个代码
window.onresize=function() {alert(1);};
When I resize any browser`s window, this function fires twice. 当我调整任何浏览器窗口的大小时,此函数会触发两次。 Why?
为什么? And how to rewrite this code that code will fire once.
以及如何重写代码将触发一次的代码。
Thanx in advance. Thanx提前。
You need a timeout to bundle the resize events. 您需要超时来捆绑调整大小事件。
var res;
window.onresize=function() {
if (res){clearTimeout(res)};
res = setTimeout(function(){console.log("resize triggered");},100);
};
This event will fire multiple times in different browsers (some once you've finished the the resize, others during). 此事件将在不同的浏览器中多次触发(有些在您完成调整大小后,其他浏览器在此期间)。
One way to get around this is to wait a certain amount of time (say half a second) after the event fires, to see if there are further updates. 解决此问题的一种方法是在事件触发后等待一定时间(比如说半秒),看是否有进一步的更新。 If not, you can proceed with the alert.
如果没有,您可以继续进行提醒。
eg 例如
var resizeTimer;
window.onresize = function(){
if (resizeTimer){
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(function(){
alert(1);
}, 500);
};
See it work on this fiddle . 看看这个小提琴的工作。
To prevent function from "firing" the same result more than once when user resize 防止函数在用户调整大小时多次“触发”相同的结果
var doc = document; //To access the dom only once
var cWidth = doc.body.clientWidth;
var newWidth = cWidth; //If you want a log to show at startup, change to: newWidth = 0
window.onresize = function (){
newWidth = doc.body.clientWidth;
if(cWidth != newWidth){
cWidth = newWidth;
console.log("clientWidth:", cWidth); //instead of alert(cWidth);
};
};
I propose other solution because I don't like the timeouts, 我建议其他解决方案,因为我不喜欢超时,
`var resized;
window.onresize = function () {
if(resized){
resized = false;
}
else{
resized = true;
alert('resize');
}
};`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.