Vue获取页面元素的相对位置的方法示例

2020-06-16 06:54:11易采站长站整理

获取元素距离文档顶部距离


返回值是一个 DOMRect 对象,这个对象是由该元素的 getClientRects() 方法返回的一组矩形的集合, 即:是与该元素相关的 CSS 边框集合。
DOMRect 对象包含了一组用于描述边框的只读属性: left、top、right 和 bottom,单位为像素。除了 width 和 height 外的属性都是相对于视口的左上角位置而言的。
getBoundingClientRect返回值
top: 元素上边框距离视窗顶部的距离
bottom: 元素下边框距离视窗顶部的距离
left: 元素左边框距离视窗左侧的距离
right: 元素右边框距离视窗左侧的距离

由于getBoundingClientRect它们会随着视窗的滚动而相应的改变,那么元素距离页面顶部的距离就是,再加上滚动距离


this.$refs.subnav.getBoundingClientRect().top + window.scrollY;
或者
this.$refs.subnav.getBoundingClientRect().top+document.documentElement.scrollTop;

window.scrollY不兼容ie9,如需兼容请看Window.scrollY

修改上方代码


if(this.$refs.subnav.getBoundingClientRect){
var top1 = this.$refs.subnav.getBoundingClientRect().top + window.scrollY
var top2 = this.$refs.subnav.getBoundingClientRect().top+document.documentElement.scrollTop;
console.log(top1)
console.log(top2)
this.scrollTop(top)
}

效果如下,不管滚动条何处位置都是一个相对文档最上面的左上角

阮一峰


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

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

    return actualTop;
}

实现原理

offsetTop可以返回元素距离offsetParent属性返回元素顶部的距离(如果父元素有定位的,那么将返回距离最近的定位元素,否则返回body元素,元素可能有多个定位元素,需要通过递归的方式层层获取距离,然后相加

特别说明: 需要将body的外边距设置为0,这样元素距离body顶部的距离就等同于距离文档顶部的距离

修改上方代码


if(this.$refs.subnav.getBoundingClientRect){
var top1 = this.$refs.subnav.getBoundingClientRect().top + window.scrollY
var top2 = this.$refs.subnav.getBoundingClientRect().top+document.documentElement.scrollTop;
// getElementTop在上方
var top3 = getElementTop(this.$refs.subnav)
console.log(top1)