2011-04-11 93 views
0

当我调整我的窗口弹出窗口停留在中心位置。它根据窗口大小显示调整。我的代码有什么问题窗口大小调整问题

.Popup 
     { 

      display: none; 
      height: 400px; 
      width: 400px; 
      position: fixed; 
      background-color: white; 
      z-index: 9999; 
     } 
    </style> 
    <script type="text/javascript"> 
     onload = function() { 
      var height = "innerHeight" in window 
       ? window.innerHeight 
       : document.documentElement.offsetHeight; 
      $('#popup').css({ 
       'margin-top': (height/2) - (200), 
       'margin-left': (document.body.offsetWidth/2) - (200) 
      }); 

      document.getElementById("popup").style.display = "inline"; 
     } 
    </script> 

回答

1

如果您希望弹出窗口相对于窗口保持居中,则需要使用负边距和基于百分比的定位。

此外,您的CSS引用了一个名为.Popup的类和您的JavaScript ID为#popup的ID。你可能想要整理一下。下面是一些示例CSS:

.Popup 
{ 
    display: block; 
    position: fixed; 
    height: 400px; 
    width: 400px; 
    top: 50%; 
    left: 50%; 
    margin-top: -200px; 
    margin-left: -200px; 
    background-color: white; 
    z-index: 9999; 
} 

请注意,边距是相应尺寸的一半。 JavaScript是不必要的。

0

问题是您要为高度和宽度设置不变的像素值。例如,如果我的浏览器窗口宽度为1000像素,那么您将margin-left设置为300px。调整窗口大小时,此常数值将被保留。您可能反而想要使用百分比值并放弃javascript。例如,

#popup 
{ 
    display: none; 
    height: 400px; 
    width: 400px; 
    margin-top: 50% 
    margin-left: 50% 
    position: fixed; 
    background-color: white; 
    z-index: 9999; 
}