如何将元素绝对定位到窗口,而不管其DOM位置如何



我正在创建一个弹出覆盖模式,在正确定位/滚动时遇到问题。

我可以将模态设置为position:fixed,但如果模态的高度太高,那么模态就会溢出窗口,你就看不到它的底部。

如果我将模态设置为position:absolute,则元素将相对于具有position:relative的最近祖先定位,对吗?(或者至少看起来是这样)相反,我希望模态始终相对于窗口,这样我就可以轻松地将其居中。

有没有一种方法可以使下面的.modal相对于窗口(或元素)定位,即使元素嵌套在DOM深处,如下所示:

<body ng-app="myapp" ng-controller="mycontroller">
<div>
    <div>
         <div ui-view>
              <div class=".modal"></div>
         </div>
    </div>
</div>
</body>

如果坚持使用相同的标记并以相同的方式嵌套,那么最好使用JavaScript。

以下是一些JS代码,它提供了一种很好的方法来实现您所要求的:

function ShowDivInCenter()
{
    try
    {
        divWidth = 100;
        divHeight = 100;
        divId = 'divLogin'; // id of the div that you want to show in center
        // Get the x and y coordinates of the center in output browser's window 
        var centerX, centerY;
        if (self.innerHeight)
        {
            centerX = self.innerWidth;
            centerY = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight)
        {
            centerX = document.documentElement.clientWidth;
            centerY = document.documentElement.clientHeight;
        }
        else if (document.body)
        {
            centerX = document.body.clientWidth;
            centerY = document.body.clientHeight;
        }
        var offsetLeft = (centerX - divWidth) / 2;
        var offsetTop = (centerY - divHeight) / 2;
        // The initial width and height of the div can be set in the
        // style sheet with display:none; divid is passed as an argument to // the function
        var ojbDiv = document.getElementById(divId);
        ojbDiv.style.position = 'absolute';
        ojbDiv.style.top = offsetTop + 'px';
        ojbDiv.style.left = offsetLeft + 'px';
        ojbDiv.style.display = "block";
    }
    catch (e) {}
}

然后,您可以通过任何事件调用函数,例如:

<body onload='ShowDivInCenter();' onresize='ShowDivInCenter();'>

如果你希望它是动态的。

最新更新