[英]Get the position of a div/span tag
有人可以告诉我如何在未指定的情况下获取div
或span
元素的top
和left
位置吗?
IE:
<span id='11a' style='top:55px;' onmouseover="GetPos(this);">stuff</span>
<span id='12a' onmouseover="GetPos(this);">stuff</span>
在上面,如果我这样做:
document.getElementById('11a').style.top
返回55px
的值。 但是,如果我尝试span
'12a',则不会返回任何内容。
我在页面上有一堆div
/ span
,我无法为其指定top
/ left
属性,但我需要直接在该元素下显示一个div
。
您可以对元素的引用调用getBoundingClientRect()
方法。 然后您可以检查top
、 left
、 right
和/或bottom
属性...
var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;
如果使用 jQuery,则可以使用更简洁的代码...
var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;
这个函数会告诉你元素相对于页面的 x,y 位置。 基本上你必须遍历所有元素的父元素并将它们的偏移量加在一起。
function getPos(el) {
// yay readability
for (var lx=0, ly=0;
el != null;
lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
return {x: lx,y: ly};
}
但是,如果您只想要元素相对于其容器的 x,y 位置,那么您只需要:
var x = el.offsetLeft, y = el.offsetTop;
要将元素直接放在此元素下方,您还需要知道其高度。 这存储在 offsetHeight/offsetWidth 属性中。
var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;
虽然@nickf 的回答有效。 如果你不关心旧浏览器,你可以使用这个纯 Javascript 版本。 适用于 IE9+ 等
var rect = el.getBoundingClientRect();
var position = {
top: rect.top + window.pageYOffset,
left: rect.left + window.pageXOffset
};
正如 Alex 所指出的,您可以使用 jQuery offset() 来获取相对于文档流的位置。 使用 position() 作为其相对于父级的 x,y 坐标。
编辑:为window.load
切换document.ready
,因为load
等待所有元素,因此您可以获得它们的大小,而不是简单地准备 DOM。 根据我的经验, load
导致 Javascript 定位错误的元素更少。
$(window).load(function(){
// Log the position with jQuery
var position = $('#myDivInQuestion').position();
console.log('X: ' + position.left + ", Y: " + position.top );
});
对于只需要顶部或左侧位置的任何人,对@Nickf 的可读代码稍作修改即可解决问题。
function getTopPos(el) {
for (var topPos = 0;
el != null;
topPos += el.offsetTop, el = el.offsetParent);
return topPos;
}
和
function getLeftPos(el) {
for (var leftPos = 0;
el != null;
leftPos += el.offsetLeft, el = el.offsetParent);
return leftPos;
}
我意识到这是一个旧线程,但 @alex 的答案需要标记为正确答案
element.getBoundingClientRect()
与 jQuery 的$(element).offset()
完全匹配
它与 IE4+ 兼容... https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.