监听窗口大小事件

Tutorial: DOM操作 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0

resize

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      div {
        width: 200px;
        height: 200px;
        background-color: pink;
      }
    </style>
  </head>

  <body>
    <script>
      // 页面加载完成
      window.addEventListener("load", function () {
        var div = document.querySelector("div");
        window.addEventListener("resize", function () {
          console.log(window.innerWidth);
          if (window.innerWidth <= 800) {
            div.style.display = "none";
          } else {
            div.style.display = "block";
          }
        });
      });
    </script>
    <div></div>
  </body>
</html>
Prev: onload事件 Next: setTimeout