Skip to content

Instantly share code, notes, and snippets.

@zhaoda
Last active August 29, 2015 14:04
Show Gist options
  • Save zhaoda/3e9bf51412a93ddeb1cd to your computer and use it in GitHub Desktop.
Save zhaoda/3e9bf51412a93ddeb1cd to your computer and use it in GitHub Desktop.
获取网页元素的绝对位置

网页元素的绝对位置,指该元素的左上角相对于整张网页左上角的坐标。这个绝对位置要通过计算才能得到。

首先,每个元素都有offsetTop和offsetLeft属性,表示该元素的左上角与父容器(offsetParent对象)左上角的距离。所以,只需要将这两个值进行累加,就可以得到该元素的绝对坐标。

注意:由于在表格和iframe中,offsetParent对象未必等于父容器,所以上面的函数对于表格和iframe中的元素不适用

获取网页元素的绝对位置

function getElementLeft(element) {
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null) {
actualLeft += current.offsetLeft;
current = current.offsetParent;
}
return actualLeft;
}
function getElementTop(element) {
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null) {
actualTop += current.offsetTop;
current = current.offsetParent;
}
return actualTop;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment