📜  onresize js - Javascript (1)

📅  最后修改于: 2023-12-03 15:03:22.480000             🧑  作者: Mango

Onresize JS - JavaScript

The onresize event in JavaScript is triggered when the size of the browser window changes. It is useful when you want to manipulate the content of the page based on the size of the window. In this article, we will explore how to use onresize event in JavaScript.

Getting Started

To use onresize event in JavaScript, first, we need to create a function that will be called when the window size changes. Let's create a simple function that displays the width and height of the window on the console.

function onResize() {
  console.log(`Window width: ${window.innerWidth}, Window height: ${window.innerHeight}`);
}

After creating the function, we need to assign it to the onresize event using addEventListener function.

window.addEventListener('resize', onResize);

Now, the onResize function will be called whenever the window size changes.

Example

Let's create a simple example that changes the background color of the page based on the size of the window. If the width of the window is less than 500px, the background color will be blue, otherwise it will be red.

function onResize() {
  const body = document.querySelector('body');
  
  if (window.innerWidth < 500) {
    body.style.backgroundColor = 'blue';
  } else {
    body.style.backgroundColor = 'red';
  }
}

window.addEventListener('resize', onResize);

In the above example, we first select the body element using querySelector. Then, we check the width of the window using window.innerWidth property. If the width is less than 500px, we change the background color of the body element to blue, otherwise we change it to red.

Conclusion

In this article, we learned how to use onresize event in JavaScript. We created a function that is called when the window size changes and used it to manipulate the content of the page based on the size of the window. We also saw a simple example that changes the background color of the page based on the width of the window.