首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >定位div相对于另一个元素居中

问定位div相对于另一个元素居中
EN

Stack Overflow用户
提问于 2013-09-17 19:09:32
回答 3查看 50关注 0票数 0

我正在使用某种覆盖来声明页面(或某些元素)正在被加载。我正在尝试定位div,上面写着:“正在加载...”位于页面或目标元素的中心。

这是我的方法,但它根本不起作用...

代码语言:javascript
复制
var left, top,
    position = 'fixed';

if (this.container !== 'body'){
  position = 'absolute';
}

left = (window.innerWidth - this.element.offsetWidth) / 2;
top = (window.innerHeight/2) - (this.element.offsetHeight/ 2);

this.modal.style.left = left + 'px';
this.modal.style.top = top + 'px';
this.modal.style.position = position;

请声明没有jQuery,我也不打算使用jQuery。

EN

回答 3

Stack Overflow用户

发布于 2013-09-17 19:15:04

如果你打算对所有动作通知使用相同的div,我指的是不同的元素,但是相同的div,如果不使用JS,你将无法做到这一点。但至少jQuery会让编码变得更容易:

您可以使用.offset查找当前元素相对于整个文档的位置,使用element的.width()使用.height()来计算弹出窗口坐标。

票数 1
EN

Stack Overflow用户

发布于 2013-09-17 19:18:04

代码语言:javascript
复制
Use css to center the "cover" over the loading part, then use jquery to hide the "cover" div when completed.

<html>
    <style>
        #outer
        {
            position: absolute;
            left: 10px;
            top: 10px;
            height: 300px;
            width: 300px;
            border: 1px solid black;
            background-color: red;
        }

        #loading
        {
            position: absolute; 
            background-color: blue; 
            width: 200px; 
            height: 200px; 
            margin-left: -100px; 
            left: 50%; 
            margin-top: -100px; 
            top: 50%;
            border: 1px solid black;
        }
    </style>
    <script src="jQuery.js"></script>
    <script>
        $(document).ready(function() {
            $("#loading").hide();
        });
    </script>
    <div id="outer">
        <div id="loading">

        </div>
    </div>
</html>
票数 0
EN

Stack Overflow用户

发布于 2013-09-17 21:40:25

终于弄明白了:

代码语言:javascript
复制
var left, top,
    position = 'fixed';

if (this.container !== 'body'){
  position = 'absolute';
}
var rect = this.element.getBoundingClientRect();

left = Math.round(((rect.width - this.modal.offsetWidth) / 2) + rect.left);
top = Math.round(((rect.height - this.modal.offsetHeight) / 2) + rect.top);

this.modal.style.left = left + 'px';
this.modal.style.top = top + 'px';
this.modal.style.position = position;

这将使元素在给定元素内正确居中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18848268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档