Javascript 窗口大小调整问题

Javascript 窗口大小调整问题,javascript,asp.net,Javascript,Asp.net,当我调整窗口大小时,弹出窗口保持在中心位置。它显示根据窗口大小进行调整。我的代码有什么问题 .Popup { display: none; height: 400px; width: 400px; position: fixed; background-color: white; z-index: 9999; }

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

.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>
.Popup
{
显示:无;
高度:400px;
宽度:400px;
位置:固定;
背景色:白色;
z指数:9999;
}
onload=函数(){
窗口中的var height=“innerHeight”
?窗内高度
:document.documentElement.offsetHeight;
$('#弹出窗口').css({
“页边距顶部”:(高度/2)-(200),
“左边距”:(document.body.offsetWidth/2)-(200)
});
document.getElementById(“弹出”).style.display=“inline”;
}

问题在于,您正在为高度和宽度设置恒定的像素值。例如,如果我的浏览器窗口是1000像素宽的onload,那么您将左边距设置为300px。调整窗口大小时,将保留此常量值。相反,您可能希望使用百分比值并放弃javascript。比如说,

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

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

此外,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是不必要的