Skip to content

Instantly share code, notes, and snippets.

@zhaoda
Last active Aug 29, 2015
Embed
What would you like to do?
获取网页元素的相对位置

网页元素的相对位置,指该元素左上角相对于浏览器窗口左上角的坐标。

有了绝对位置以后,获得相对位置就很容易了,只要将绝对坐标减去页面的滚动条滚动的距离就可以了。滚动条滚动的垂直距离,是document对象的scrollTop属性;滚动条滚动的水平距离是document对象的scrollLeft属性。

获取网页元素的相对位置

function getElementViewLeft(element) {
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null) {
actualLeft += current.offsetLeft;
current = current.offsetParent;
}
if (document.compatMode == "BackCompat"){
var elementScrollLeft=document.body.scrollLeft;
} else {
var elementScrollLeft=document.documentElement.scrollLeft;
}
return actualLeft-elementScrollLeft;
}
function getElementViewTop(element){
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null){
actualTop += current. offsetTop;
current = current.offsetParent;
}
if (document.compatMode == "BackCompat"){
var elementScrollTop=document.body.scrollTop;
} else {
var elementScrollTop=document.documentElement.scrollTop;
}
return actualTop-elementScrollTop;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment