window.onresize发射两次

时间:2013-04-04 13:26:15

标签: javascript

我是js的新手。拜托,不要痛苦地踢。 我有这个代码

    window.onresize=function() {alert(1);};

当我调整任何浏览器窗口的大小时,此功能会触发两次。为什么?以及如何重写代码将触发一次的代码。

提前完成。

4 个答案:

答案 0 :(得分:10)

您需要超时来捆绑调整大小事件。

var res;
window.onresize=function() {
    if (res){clearTimeout(res)};
    res = setTimeout(function(){console.log("resize triggered");},100);
};

live Example

答案 1 :(得分:6)

此事件将在不同的浏览器中多次触发(有些在您完成调整后,其他浏览器在此期间)。

解决此问题的一种方法是在事件触发后等待一段时间(比如说半秒),看是否有进一步的更新。如果没有,您可以继续提醒。

e.g。

var resizeTimer;
window.onresize = function(){
    if (resizeTimer){
        clearTimeout(resizeTimer);
    } 
    resizeTimer = setTimeout(function(){
        alert(1);
        }, 500);
};

this fiddle上查看它。

答案 2 :(得分:1)

防止功能在用户调整大小时多次“触发”相同的结果

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);
     };
};

答案 3 :(得分:0)

我建议其他解决方案,因为我不喜欢超时,

   `var resized;
    window.onresize = function () {
        if(resized){
            resized = false;
        }
        else{
            resized = true;
            alert('resize');
        }
    };`
相关问题