窗口调整大小的问题

时间:2011-04-11 06:33:49

标签: javascript asp.net

当我调整窗口大小时,弹出窗口保持在中心位置。它根据窗口大小显示调整。我的代码有什么不对

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

2 个答案:

答案 0 :(得分:1)

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

此外,您的CSS引用了一个名为.Popup的类,而您的JavaScript引用了一个名为#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是不必要的。

答案 1 :(得分:0)

问题在于您要为高度和宽度设置常量像素值。因此,例如,如果我的浏览器窗口是1000像素宽的onload,那么您将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;
 }