原生JS获取元素在文档中的位置

来源:互联网 发布:vue实现双向数据绑定 编辑:程序博客网 时间:2024/04/29 11:35

原生JS获取元素在文档中的位置

原生JS提供了很多关于元素信息的属性

这里写图片描述

具体就不总结了

元素在页面上的位置有绝对位置和相对位置


绝对位置

网页元素的绝对位置,指该元素的左上角相对于整张网页左上角的坐标。这个绝对位置要通过计算才能得到。
首先,每个元素都有offsetTop和offsetLeft属性,表示该元素的左上角与父容器(offsetParent对象)左上角的距离。所以,只需要将这两个值进行累加,就可以得到该元素的绝对坐标。

但这里要注意一个问题:要计算offsetParent的边框宽度。当左右边框宽度相同时,可以通过(offsetWidth-clientWidth)/2得到水平方向上一边框宽度。

// 获取元素在页面上的绝对位置    function getElementPageLeft(element){        var actualLeft=element.offsetLeft;        var parent=element.offsetParent;        while(parent!=null){            actualLeft+=parent.offsetLeft+(parent.offsetWidth-parent.clientWidth)/2;            parent=parent.offsetParent;        }        return actualLeft;    }    function getElementPageTop(element){        var actualTop=element.offsetTop;        var parent=element.offsetParent;        while(parent!=null){            actualTop+=parent.offsetTop+(parent.offsetHeight-parent.clientHeight)/2;            parent=parent.offsetParent;        }        return actualTop;    }



相对位置

网页元素的相对位置,指该元素左上角相对于浏览器窗口左上角的坐标。
有了绝对位置以后,获得相对位置就很容易了,只要将绝对坐标减去页面的滚动条滚动的距离就可以了。

//获取元素在页面上的相对于窗口的位置    function getElementViewLeft(element){        var actualLeft=element.offsetLeft;        var parent=element.offsetParent;        //获取页面滚动距离        var scrollLeft=document.body.scrollLeft||document.documentElement.scrollLeft        while(parent!=null){            actualLeft+=parent.offsetLeft+(parent.offsetWidth-parent.clientWidth)/2;            parent=parent.offsetParent;        }        return actualLeft-scrollLeft;    function getElementViewTop(element){        var actualTop=element.offsetTop;        var parent=element.offsetParent;        var scrollTop=document.body.scrollTop||document.documentElement.scrollTop        while(parent!=null){            actualTop+=parent.offsetTop+(parent.offsetHeight-parent.clientHeight)/2;            parent=parent.offsetParent;        }        return actualTop-scrollTop;    }



获取元素的相对位置,JS还提供了一种更简单的方法:Element.getBoundingClientRect()

Element.getBoundingClientRect()返回一个对象,对象包含了元素距离窗口的位置属性:left、right、top、bottom

这里写图片描述
注意:要考虑浏览器是否支持此方法!



参考链接:阮一峰的博客

原创粉丝点击