还是废话不多说,直接上代码
/**
* getElementPosition
*
* @description 获得目标元素x,y
* @param {target} 目标元素
* @return {object} {x, y}
*
*/
const getElementPosition = element => {
let [actualLeft, actualTop, current] = [
element.offsetLeft,
element.offsetTop,
element.offsetParent,
];
while (current !== null) {
actualLeft += current.offsetLeft;
actualTop += current.offsetTop;
current = current.offsetParent;
}
let [elementScrollLeft, elementScrollTop] = [0, 0];
if (document.compatMode === 'BackCompat') {
elementScrollLeft = document.body.scrollLeft;
elementScrollTop = document.body.scrollTop;
} else {
elementScrollLeft = document.documentElement.scrollLeft;
elementScrollTop = document.documentElement.scrollTop;
}
return {
x: actualLeft - elementScrollLeft,
y: actualTop - elementScrollTop,
};
};
拿去用吧!!!