简体   繁体   中英

Javascript onresize event not firing

I'm trying to adjust the border width of my background image when the browser is resized. I'm calling that function onload and onresize. Unfortunately only the onload one is being called. So when I resize the browser I have to refresh the page to see the updated border width. No error messages in the console, everything else works perfectly- it's as though I hadn't even written an on resize listener.

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

The problem is you are only defining your borderwidth the first time the javascript loads. It needs to be changed when the window is changed. Something along the lines of:

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

Untested, try it and see if that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM