data(){
return{
app:'',
scrollTop:'',
tab:['index','home','about','link'], // 元素的id
currentIndex:0 // 记录高亮的位置下标
}
}
mounted () {
this.app = document.querySelector('#app')
this.app.addEventListener('scroll', this.scrollToTop)
},
destroyed () {
this.app.removeEventListener('scroll', this.scrollToTop)
},
methods:{
scrollToTop(){
this.scrollTop = this.app.scrollTop
const clinentHeight = document.body.clientHeight / 2 // 为了元素到屏幕中间就高亮,而不是顶部
this.tab.forEach((item,index)=>{
const top=document.getElementById(item).getBoundingClientRect().top
const height=document.getElementById(item).getBoundingClientRect().height
if(top <= clinetHeight && -top < height){
this.currentIndex = index
}
)}
}
}
Vue锚点滚动高亮
最新推荐文章于 2024-07-26 11:41:15 发布