简体   繁体   中英

Always listen to window screen changes

How do I make the code always respond to the changes in screen size?

I remember there is one globalEventHandler can do this but I'm not sure which one...

For example, the div #test-02 will always automatically adjust its width to 1/3 of the div #test-01 . The problem is that as we use the developer tool (f12) to resize the window, the width of div #test-01 is keep changing but the code won't respond to it anymore...Unless we reload the page...

 const test01 = document.querySelector('#test-01'); const test02 = document.querySelector('#test-02'); const data = test01.getBoundingClientRect().width; test02.style.width = `${data / 3}px`;
 #test-01 { width: 100vw; height: 50vh; background-color: grey; display: flex; justify-content: center; align-items: center; } #test-02 { height: 100%; background-color: orange; }
 <div id="test-01"> <div id="test-02"></div> </div>

To listen for window screen changes, you can use

window.addEventListener("resize", callback)

This will listen for resize events on the window, and execute the callback function if such an event occurs. So you could put the code which resizes your elements relative to each other into the callback, so that it is executed on every window resize. (The callback will not be run on page load, so you would have to run your code outside of the event handler once too.)

The following code should work in your case:

const test01 = document.querySelector('#test-01');
const test02 = document.querySelector('#test-02');

function onResize() {
  const data = test01.getBoundingClientRect().width;
  test02.style.width = `${data / 3}px`;
}

window.addEventListener("resize", onResize, {passive: true})
onResize()

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