通过 JavaScript 获取元素的位置 [英] Get position of element by JavaScript
本文介绍了通过 JavaScript 获取元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我见过许多脚本可以捕捉页面中元素/对象的 x 和 y 位置.但是,当网页使用正文的边距或其他元素、绝对/相对元素等时,我总是无法捕捉 x 和 y.
I've seen dozens of scripts that can catch the x and y position of an element/object within the page. But I am always having trouble with catching the x and y when the webpage is using margins at the body, or other elements, absolute/relative elements, such like that.
有没有一种解决方案可以提供准确的位置,无论使用什么边距或填充?
Is there a solution which provides the exact position, no matter what margins or paddings are used?
推荐答案
我在这个Web中使用以下代码移动div框以跟随光标输入法网站
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],
Its return an array [left,top],
这篇关于通过 JavaScript 获取元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文