简体   繁体   中英

Load javascript on window resize

My page

Giving my different sections their own height to be able to make them overlap each other. I got it working, but the javascript only loads when the page refreshes.

Is it possible to add some code so that my code updates when the window size changes in real time?

And, I understand that my way of distinguishing the three different panels is a shortcut. Is it possible to write the code so that it calculates each unit by itself, which would make it easier if I want to add sections.

let div = document.querySelector(".panel-01")
        var height = document.querySelector(':root');
        height.style.setProperty('--height', div.clientHeight + "px");          

let div2 = document.querySelector(".panel-02")
        var height = document.querySelector(':root');
        height.style.setProperty('--height-2', div2.clientHeight + "px");          

let div3 = document.querySelector(".panel-03")
        var height = document.querySelector(':root');
        height.style.setProperty('--height-3', div3.clientHeight + "px");          
.panel-01 {
    top:calc(100vh - var(--height));
}

.panel-02 {
    top:calc(100vh - var(--height-2));
}

.pangel-03 {
    top:calc(100vh - var(--height-3));
}

You should read about responsive Concept once. This concept will always be useful for you.

But if you want to perform any action when the window is resized, then this code will come in handy for you. In this way you can apply the resize event to the window. Whenever the window is resized, it will run the given function.

TRY TO RESIZE YOUR WINDOW AND SEE RESULT

 window.addEventListener('resize', function(event){ var newWidth = window.innerWidth; var newHeight = window.innerHeight; // Your code. // Exmple: document.getElementById("size").innerHTML = `newWidth: ${newWidth}, newHeight: ${newHeight}`; });
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <p id="size"></p> <script src="script.js"></script> </body> </html>

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