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) console.log(top2) console.log(top3) this.scrollTop(top) }
效果如下
总结三种方法获取元素距离文档顶部位置
dom.getBoundingClientRect().top + window.scrollY; 或者 dom.getBoundingClientRect().top+document.documentElement.scrollTop; 或者 function getElementTop(element){ var actualTop = element.offsetTop; var current = element.offsetParent; while (current !== null){ actualTop += current.offsetTop; current = current.offsetParent; } return actualTop; }
参考文章