我见过很多可以捕捉页面内元素/对象的 x 和 y 位置的脚本。但是当网页在正文或其他元素、绝对/相对元素等使用边距时,我总是无法捕捉 x 和 y。
无论使用什么边距或填充,是否有提供准确位置的解决方案?
我见过很多可以捕捉页面内元素/对象的 x 和 y 位置的脚本。但是当网页在正文或其他元素、绝对/相对元素等使用边距时,我总是无法捕捉 x 和 y。
无论使用什么边距或填充,是否有提供准确位置的解决方案?
我使用以下代码移动 div 框以跟随此Web IME 站点中的光标
function xy(x) {
o = document.getElementById(x);
var l =o.offsetLeft; var t = o.offsetTop;
while (o=o.offsetParent)
l += o.offsetLeft;
o = document.getElementById(x);
while (o=o.offsetParent)
t += o.offsetTop;
return [l,t];
}
它返回一个数组 [left,top],
获取确切位置只需将 offsetLefts 和 offsetTops 递归地添加到offsetParents中:
function getPos(ele){
var x=0;
var y=0;
while(true){
x += ele.offsetLeft;
y += ele.offsetTop;
if(ele.offsetParent === null){
break;
}
ele = ele.offsetParent;
}
return [x, y];
}
顺便说一句,这个解决方案的运行速度可能比上面的其他解决方案快两倍,因为我们只循环一次。
offsetParent
和其他偏移函数是旧的......使用getBoundingClientRect
函数......使用这个:
function getAbsPosition(element) {
var rect = element.getBoundingClientRect();
return {x:rect.left,y:rect.top}
}
现在你可以像这样使用它
<div style="margin:50px;padding:50px;" id="myEl">lol</div>
<script type="text/javascript">
var coords = getAbsPosition( document.getElementById('myEl') );
alert( coords.x );alert( coords.y );
</script>
别担心......无论元素有多少边距、位置或填充,它总是有效的
YOU's code is downright bad, and I've some improvements on Pacerier's to give, so I'll post my own answer:
function getPos(el, rel)
{
var x=0, y=0;
do {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
}
while (el != rel)
return {x:x, y:y};
}
If is just used as getPos(myElem)
will return global position. If a second element is included as an argument (i.e. getPos(myElem, someAncestor)
) that is an ancestor/parent of the first (at least somewhere up the chain) then it will give the position relative to that ancestor. If rel
is not given (i.e. is left undefined
), then it purposefully uses !=
instead of !==
because it should stop when el
gets to null
and rel
is undefined
as well, so the non-strict equality is purposeful, don't change it. It also returns an object, since that's a bit more readable in usage than an array (and so you can do something like getPos().x
).
This is derived from Pacerier's solution, so if you're gonna upvote this, consider upvoting his too.