如何精确地获取页面中元素的位置

在IE,Chrome等浏览器中提供一个getBoundingClientRect()方法,这个方法返回一个矩形对象,包括4个属性:lefttopbottomright,这些属性给出了元素在页面中相对于视口的位置。

需要注意的是,在IE8以及低版本的IE中,会认为(2,2)为文档的左上角,其余的浏览器则会以(0,0)作为左上角,所以在不同的浏览器中要对该起点坐标进行统一化处理。

function getElementLeft(element) {
    var actualLeft = element.offsetLeft;
    var current = element.offsetParent;
    while (current !== null) {
        actualLeft += current.offsetLeft;
        current = current.offsetParent;
    }
    return actualLeft;
}

function getElementTop(element) {
    var actualTop = element.offsetTop,
        current = element.offsetParent;

    while (current !== null) {
        actualTop += current.offsetTop;
        current = current.offsetParent;
    }

    return actualTop;
}

function getBoundingClientRect(element) {
    var scrollTop = document.documentElement.scrollTop,
        scrollLeft = document.documentElement.scrollLeft;

    if (element.getBoundingClientRect) {
        if (typeof arguments.callee.offset !== 'number') {
            var temp = document.createElement('div');
            temp.style.cssText = 'position: absolute;left:0;top:0';
            document.body.appendChild(temp);
            arguments.callee.offset = -temp.getBoundingClientRect().top - scrollTop;
            document.body.removeChild(temp);
            temp = null;
        }
        var rect = element.getBoundingClientRect(),
            offset = arguments.callee.offset;

        return {
            left: rect.left + offset,
            top: rect.top + offset,
            right: rect.right + offset,
            bottom: rect.bottom + offset
        }
    } else {
        var actualLeft = getElementLeft(element),
            actualTop = getElementTop(element);

        return {
            left: actualLeft - scrollLeft,
            top: actualTop - scrollTop,
            right: actualLeft + element.offsetWidth - scrollLeft,
            bottom: actualTop + element.offsetHeight - scrollTop
        }
    }
}

上述减去视口的scrollTop,是为了防止调用这个函数时窗口被滚动了。

对于不支持getBoundingClientRect()的浏览器,可以通过特殊手段来获取信息。一般来说,rightleft的差值与offsetWidth的值相等,bottomtop的差值与offsetHeight的值相等。

本文参考自:<<Javascript高级程序设计>>

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注