DOM onresize event

前端 未结 7 553
无人共我
无人共我 2020-12-02 19:06

If I have this

window.onresize = function() {
  alert(\'resized!!\');
};

My function gets fired multiple times throughout the res

7条回答
  •  不思量自难忘°
    2020-12-02 19:48

    Not sure if this might help, but since it seems to be working perfectly, here it is. I have taken the snippet from the previous post and modified it slightly. The function doCenter() first translates px to em and than substracts the width of the object and divides the remainder by 2. The result is assigned as left margin. doCenter() is executed to center the object. timeout fires when the window is resized executing doCenter() again.

    function doCenter() {
    document.getElementById("menuWrapper").style.position = "fixed";
    var getEM = (window.innerWidth * 0.063);
    document.getElementById("menuWrapper").style.left = (getEM - 40) / 2 + "em";
    }
    
    doCenter();
    
    var timeOut = null;
    var func = function() {doCenter()};
    window.onresize = function(){
        if (timeOut != null) clearTimeout(timeOut);
        timeOut = setTimeout(func, 100);
    };
    

提交回复
热议问题