1,绝对位置与相对位置
(1)网页元素的绝对位置,指该元素的左上角相对于整张网页左上角的坐标。无论网页滚动条如何滚动,它都是不会变化的。使用下面方法可以获取元素的绝对位置坐标:
// 获取元素的绝对位置坐标(像对于页面左上角)
function getElementPagePosition(element){
//计算x坐标
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null){
actualLeft += current.offsetLeft;
current = current.offsetParent;
}
//计算y坐标
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null){
actualTop += (current.offsetTop+current.clientTop);
current = current.offsetParent;
}
//返回结果
return {x: actualLeft, y: actualTop}
}
(2)网页元素的相对位置,是指元素左上角相对于浏览器窗口可视区域(视区:viewport)左上角的坐标。它会随着滚动条滚动而变化。使用下面方法可以获取元素的相对位置坐标(原理就是先获取绝对位置,然后再减去滚动距离):
// 获取元素的绝对位置坐标(像对于浏览器视区左上角)
function getElementViewPosition(element){
//计算x坐标
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null){
actualLeft += (current.offsetLeft+current.clientLeft);
current = current.offsetParent;
}
if (document.compatMode == "BackCompat"){
var elementScrollLeft=document.body.scrollLeft;
} else {
var elementScrollLeft=document.documentElement.scrollLeft;
}
var left = actualLeft - elementScrollLeft;
//计算y坐标
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null){
actualTop += (current.offsetTop+current.clientTop);
current = current.offsetParent;
}
if (document.compatMode == "BackCompat"){
var elementScrollTop=document.body.scrollTop;
} else {
var elementScrollTop=document.documentElement.scrollTop;
}
var right = actualTop-elementScrollTop;
//返回结果
return {x: left, y: right}
}
原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_2260.html