JavaScript如何获得一个DOM元素的绝对位置?(获取元素位置,不依赖框架)

JavaScript如何获得一个DOM元素的绝对位置?(获取元素位置,不依赖框架)

function offset(ele) {
    var top = ele.offsetTop;
    var left = ele.offsetLeft;
    while (ele.offsetParent) {
        ele = ele.offsetParent;
        if (window.navigator.userAgent.indexOf('MSTE 8') > -1) {
            top += ele.offsetTop;
            left += ele.offsetLeft;
        } else {
            top += ele.offsetTop + ele.clientTop;
            left += ele.offsetLeft + ele.clientLeft;
        }
    }
    return {
        left: left,
        top: top
    }

}
var oImg = document.getElementById('img1');
console.log(offset(oImg).top, offset(oImg).left);

知识点:

(1)判断浏览器版本用window.navigator.userAgent

(2)IE8中offsetTop和offsetLeft包含border的值

你可能感兴趣的:(JavaScript)