2014-05-23 126 views
1

我试图调整浏览器调整大小时背景图像的边框宽度。我在调用onload和onresize函数。不幸的是只有正在调用的onload。所以,当我调整浏览器的大小时,我必须刷新页面以查看更新后的边框宽度。控制台中没有错误消息,其他所有内容都能正常工作 - 就好像我甚至没有写过调整大小监听器一样。Javascript onresize event not firing

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

回答

2

问题是,你只定义你borderwidth首次JavaScript的负荷。当窗口改变时它需要改变。沿线的东西:

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

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

+0

哦,是的!你的代码几乎完美 - 非常感谢!我只需要替换“getBorderWidth();”为你的“var borderWidth = getBorderWidth();” –