2015-11-02 85 views
0

我的页面中有一个div元素。下面是功能我想它有:为什么我在窗口中删除'resize'事件失败?

  1. 填写浏览器窗口,也就是最大化,它的点击
  2. 它最大化后,div元素保持最大化浏览器窗口大小变化时之后。
  3. 当它被最大化时,点击它可以在最大化之前将div恢复到其原始大小。

为了实现第二点,我在窗口上注册了一个resize事件来保持最大化状态。当涉及到第三点时,resize事件被删除。但是,似乎resize事件未能被删除,因为当我调整浏览器窗口时,div元素再次被最大化。 有人可以告诉我发动机盖下面会发生什么吗?

http://jsbin.com/pokirokahe/edit?html,output

!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>

回答

1

每次触发click事件时,都定义了一个名为fullfill的函数,所以函数fullfill与您的addEventListener不等于您删除的函数。 如果您希望网页正确运行,您应该在click eventListner中定义名为fullfill的函数。

0

嗯,我认为这是最好使用CSS在这种情况下,因为你需要在div最大化并获得浏览器的大小,使用的位置绝对或固定到div并给它的高度:100%,宽度:100%,它会自动重新调整大小与浏览器,它会为您节省JS事件的麻烦。

+0

谢谢。它运作良好。我会采用这种方法。 –

+0

但我仍然想知道我的活动出了什么问题? –