Javascript 从左侧查找元素的距离
我使用技巧将元素集中在屏幕中间,例如Javascript 从左侧查找元素的距离,javascript,css,Javascript,Css,我使用技巧将元素集中在屏幕中间,例如 .info{ z-index: 0; width: 700px; height: 500px; margin: auto; position: absolute; top: 0px; left: 0; bottom: 0; right: 0; } 在该元素中,我有另一个元素,如何从左上方检索该元素的距离?我尝试了o
.info{
z-index: 0;
width: 700px;
height: 500px;
margin: auto;
position: absolute;
top: 0px;
left: 0;
bottom: 0;
right: 0;
}
在该元素中,我有另一个元素,如何从左上方检索该元素的距离?我尝试了offsetLeft
属性,但它返回了0,因为我提到的技巧是将所有属性都设置为0,我如何克服这个问题?
html
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
因为您使用边距定位框,并将顶部
、左侧
、右侧
、底部
属性设置为0
,所以框与其父对象之间不会有任何距离
但是您可以得到计算的边距值,这些值是指内容和父元素之间的空间
var el = document.querySelector('.info');
var style = window.getComputedStyle(el);
var top = style['margin-top'],
left = style['margin-left'];
alert(
"Top:" + top + '\n' +
"Left:" + left
);
不太清楚。。请添加HTML代码好吗?alert(顶部)在[Window][Object]中显示,它在示例中非常适合我:https://jsfiddle.net/af746bdg/2/
。当然,您必须将像素字符串值转换为数字!是的,我知道,left属性很好,但是top总是在我的casevar el=document.querySelector('.info')中产生[window][Object];var style=window.getComputedStyle(el);var-top=样式['margin-top'];var left=样式['margin-left'];警报(顶部)与gabe发布的cde相同。编写style['margin-top']
而不是style['top']
。因为在这种情况下,您无法获得定位属性,因为它们被设置为零!但是边距属性显示距离,因为您使用margin
属性定位元素!
var el = document.querySelector('.info');
var style = window.getComputedStyle(el);
var top = style['margin-top'],
left = style['margin-left'];
alert(
"Top:" + top + '\n' +
"Left:" + left
);