为什么我删除'调整大小'窗口上的事件

Why I failed removing 'resize' event on window?

本文关键字:窗口 事件 调整 删除 为什么      更新时间:2023-09-26

我的页面中有一个div元素。以下是我希望它具有的功能:

  1. 点击后,填写浏览器窗口,即最大化
  2. 在最大化之后,div元素在浏览器窗口大小更改时保持最大化
  3. 当它最大化时,单击它会将div恢复到最大化之前的原始大小

为了实现第二点,我在窗口上注册了一个调整大小事件,以保持最大化状态。当到达第三个点时,调整大小事件将被删除。然而,似乎无法删除resize事件,因为当我调整浏览器窗口时,div元素再次被最大化。有人能告诉我引擎盖下面发生了什么吗?

http://jsbin.com/pokirokahe/edit?html,输出

!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    div {
      width: 200px;
      height: 200px;
      border: 2px solid blue;
      background: gray;
    }
    body {
      margin: 0;
    }
  </style>
</head>
<body>
  <div></div>
  <script>
    var domDiv = document.getElementsByTagName("div")[0];
    var maximized = false;
    var originSize = {};
    originSize.w = parseFloat(getComputedStyle(domDiv, null).width);
    originSize.h = parseFloat(getComputedStyle(domDiv, null).height);
    domDiv.addEventListener("click", function() {
      if (!maximized) {
        fullfill();
        maximized = true;
        console.log("maximized true, adding event listener");
        window.addEventListener("resize", fullfill);
      } else {
        this.style.width = originSize.w + "px";
        this.style.height = originSize.h + "px";
        console.log("maximized false, removing event listener");
        window.removeEventListener("resize", fullfill);
        maximized = false;
      }
      function fullfill() {
        var screensize = getViewportSize();
        console.log(screensize.w + " " + screensize.h);
        var divBorder = {
          top: parseFloat(getComputedStyle(domDiv, null).borderTopWidth),
          bottom: parseFloat(getComputedStyle(domDiv, null).borderBottomWidth),
          left: parseFloat(getComputedStyle(domDiv, null).borderLeftWidth),
          right: parseFloat(getComputedStyle(domDiv, null).borderRightWidth)
        };
        domDiv.style.width = screensize.w - divBorder.left - divBorder.right + "px";
        domDiv.style.height = screensize.h - divBorder.top - divBorder.bottom + "px";
      }
    });
    function getViewportSize(w) {
      w = w || window;
      if (w.innerWidth != null) return {
        w: w.innerWidth,
        h: w.innerHeight
      };
      var d = w.document;
      if (document.compatMode == "CSS1Compat")
        return {
          w: d.documentElement.clientWidth,
          h: d.documentElement.clientHeight
        };
      return {
        w: d.body.clientWidth,
        h: d.body.clientHeight
      };
    }
  </script>
</body>
</html>

每次触发click事件时,都定义了一个名为fullfill的函数,因此addEventListener中的函数fullfill不等于您删除的函数。如果您希望web正确运行,您应该在click事件列表器中定义名为fullfill的函数。

我认为在这种情况下最好使用css,因为你需要将div最大化并获得浏览器的大小,使用div的绝对或固定位置,并赋予它高度:100%,宽度:100%,它将自动随浏览器重新调整大小,这将为你省去JS事件的麻烦。