窗口大小调整问题

Window resizing problem

本文关键字:问题 调整 窗口大小      更新时间:2023-09-26

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

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

如果你想让弹出框相对于窗口保持居中,你需要使用负边距和基于百分比的定位。

同样,你的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;
}

请注意,边距是各自尺寸的一半。

问题是你为高度和宽度设置了恒定的像素值。例如,如果我的浏览器窗口是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;
 }