Javascript 将div定位在相对于另一个元素的中心位置
我正在使用某种覆盖来声明页面(或某些元素)正在加载。我正在尝试定位Javascript 将div定位在相对于另一个元素的中心位置,javascript,html,css,Javascript,Html,Css,我正在使用某种覆盖来声明页面(或某些元素)正在加载。我正在尝试定位div,它说:“加载…”位于页面或目标元素的中心 这是我的方法,但根本不起作用 var left, top, position = 'fixed'; if (this.container !== 'body'){ position = 'absolute'; } left = (window.innerWidth - this.element.offsetWidth) / 2; top = (window.inne
div
,它说:“加载…”位于页面或目标元素的中心
这是我的方法,但根本不起作用
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。如果您要对所有操作通知使用相同的div,我指的是不同的元素,但相同的div,如果不使用JS,您将无法执行此操作。但至少jQuery会让编写代码变得更容易: 您可以使用元素的
.width()
查找当前元素相对于整个文档的位置,然后使用元素的.height()
计算弹出坐标。使用css将“cover”居中放置在加载部分上,然后在完成后使用jquery隐藏“cover”div。
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>
#外
{
位置:绝对位置;
左:10px;
顶部:10px;
高度:300px;
宽度:300px;
边框:1px纯黑;
背景色:红色;
}
#装载
{
位置:绝对位置;
背景颜色:蓝色;
宽度:200px;
高度:200px;
左边距:-100px;
左:50%;
利润上限:-100px;
最高:50%;
边框:1px纯黑;
}
$(文档).ready(函数(){
$(“#加载”).hide();
});
终于明白了:
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;
这将使元素正确地位于给定元素的中心。我确实想使用JavaScript,但仅使用CSS无法实现这一点。在这种情况下,我建议您将这3种jQuery方法应用到您的应用程序中。它将允许您拥有跨浏览器解决方案。您不想使用它的原因是什么?不必为所有内容向页面添加jQuery!好啊然后只需使用这些方法,并制作自己的小库。为什么不使用CSS呢?因为我需要中继的位置上的元素是不确定的。如果我希望它在ID为“代码> AWESOMECONCONTRONTION的DIV中间”,那么这将不起作用。这是在另一个div中吗?这是一种插件,我不知道哪个是页面中的内容,可能
容器不是body,而是页面中的其他元素。我想用一个覆盖层和一条消息来覆盖元素,说明正在加载。这就是为什么CSS解决方案无法在加载内容后删除封面的其他单词中工作的原因?很抱歉,这不符合任何要求:第一个是使用jQuery,第二个是您的div没有针对任何元素定位。我想抓取一个DOM元素,并根据抓取的元素定位一个DIV。