动态获得目标高度
先设置目标标签
<div ref="pronbit">
<div>我的动态高度</div>
</div>
mounted(){
window.addEventListener('scroll',this.handleScrollx,true)
},
页面加载时获取目标距离顶部的高度
methods: {
handleScrollx() {
console.log('滚动高度',window.pageYOffset)
console.log('距离顶部高度',this.$refs.pronbit.getBoundingClientRect().top)
},
}
获得高度后滚到到目标标签位置
let ttop = this.$refs.pronbit.getBoundingClientRect().top
console.log('top',ttop);
获取高度后下方执行滚动操作
this.$nextTick(function () {
window.scrollTo({'behavior': 'smooth', 'top': ttop})
})
记得用延迟执行 setTimeout() 加载滚动操作;