JavaScript/元素位置
来自康健生活
引言
元素在当前坐标系中的位置
获取元素在当前文档区域坐标系中的坐标,考虑 transform 等 css 属性影响其内部坐标系定位的问题。
function getPosition(element) {
const actualLeft = element.offsetLeft;
const actualTop = element.offsetTop;
const current = element.offsetParent;
// 循环直到根元素
while (current !== null) {
actualLeft += current.offsetLeft;
actualTop += current.offsetTop;
current = current.offsetParent;
}
return {
left: actualLeft,
top: actualTop
};
}
元素在当前视窗坐标系中的位置
function getPosition(element){
// 获取元素相对浏览器视窗window的左、上坐标
let {left: _x, top: _y} = element.getBoundingClientRect();
// 与 html 或 body 元素的滚动距离相加就是元素相对于文档区域 document 的坐标位置
_x += document.documentElement.scrollLeft || document.body.scrollLeft;
_y += document.documentElement.scrollTop || document.body.scrollTop;
return {
left: _x,
top: _y
};
}
滚动条
function getScrollOffset(w){
w = w || window;
if(w.pageXOffset != null)
return { x: w.pageXOffset, y: w.pageYOffset };
var d = document;
//标准模式
if(document.compatMode == "CSS1Compat")
return { x: d.documentElement.scrollLeft, y:d.documentElement.scrollTop };
//怪异模式
return { x: d.body.scrollLeft, y: d.body.scrollTop };
}
视窗
function getViewportSize(w){
//使用指定窗口,如果不带参数则使用当前窗口
w = w || window;
if(w.innerWidth != null)
return { w: w.innerWidth, h: w.innerHeight };
var d = w.document;
//标准模式
if(document.compatMode == "CSS1Compat")
return { w: d.documentElement.clientWidth, h: d.cocumentElement.clientHeight };
//怪异模式
return { w: d.body.clientWidth, h: d.body.clientHeight }
}
No categories