【问题标题】:Javascript onresize event not firingJavascript onresize 事件未触发
【发布时间】:2014-05-24 00:45:30
【问题描述】:

我正在尝试在调整浏览器大小时调整背景图像的边框宽度。我正在调用该函数 onload 和 onresize。不幸的是,只有 onload 一个被调用。因此,当我调整浏览器大小时,我必须刷新页面才能看到更新后的边框宽度。控制台中没有错误消息,其他一切都运行良好 - 就好像我什至没有写一个 on resize 监听器。

w = window.innerWidth;
h = window.innerHeight;
hypotenuse = Math.sqrt(w * w + h * h);
borderWidth = window.hypotenuse/74;

function adjustBorder(width) {
    document.getElementById('tileBlock').style.borderWidth = width + 'px';
}

window.onload=function(){
adjustBorder(borderWidth);
}

window.onresize = function() {
    adjustBorder(borderWidth);
}



 <div class="wrapper" id="tileBlock"></div>



    #tileBlock {
    position: fixed;
    background-color: #0b0b0b;
    background-position: center;
    background-repeat: no-repeat;
    background-image: url(photo.jpg);
    border: 20px solid #fff;
    background-size: cover;  
    }

【问题讨论】:

    标签: javascript javascript-events


    【解决方案1】:

    问题是您只是在第一次加载 javascript 时定义您的 borderwidth。更改窗口时需要更改。类似的东西:

    function adjustBorder(width) {
        document.getElementById('tileBlock').style.borderWidth = width + 'px';
    }
    
    window.onload=function(){
        var borderWidth = getBorderWidth();
        adjustBorder(borderWidth);
    }
    
    window.onresize = function() {
        var borderWidth = getBorderWidth();
        adjustBorder(borderWidth);
    }
    
    function getBorderWidth(){
        w = window.innerWidth;
        h = window.innerHeight;
        hypotenuse = Math.sqrt(w * w + h * h);
        borderWidth = window.hypotenuse/74;
    }
    

    未经测试,试试看是否有帮助。

    【讨论】:

    • 哦,是的!你的代码几乎是完美的——非常感谢!我只需要替换“getBorderWidth();”为您的“var borderWidth = getBorderWidth();”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    相关资源
    最近更新 更多