5

我是 js 新手。请不要痛苦地踢。我有这个代码

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

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

提前谢谢。

4

4 回答 4

10

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

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

现场示例

于 2013-04-04T13:37:21.850 回答
6

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

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

例如

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

看到它在这个小提琴上工作。

于 2013-04-04T13:33:41.247 回答
2

当用户调整大小时,防止函数多次“触发”相同的结果

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);
     };
};
于 2013-07-21T07:35:12.733 回答
0

我提出其他解决方案,因为我不喜欢超时,

   `var resized;
    window.onresize = function () {
        if(resized){
            resized = false;
        }
        else{
            resized = true;
            alert('resize');
        }
    };`
于 2014-09-09T00:48:17.523 回答