内容标题绑定title-nav样式类
const elements = document.querySelectorAll(".title-nav");
const titles=[]
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
let node={
id:i,
title:element.innerText,
element: element,
}
titles.push(node)
}
this.navList=titles
window.addEventListener("scroll",debounce(this.scrollHander,200))
scrollToView(item) {
this.currentTitle=item.id
item.element.scrollIntoView({ behavior: "smooth" })
},
scrollHander(){
if(this.navList[0].element.getBoundingClientRect().top>300){
this.currentTitle=0
return
}
for(let i=0,len= this.navList.length;i<len;i++){
let top=this.navList[i].element.getBoundingClientRect().top
// 切换区域顶部300px
if(top>=0&&top<=300){
this.currentTitle=this.navList[i].id
break
}
// 视图第一标题300px外
else if(top<0&&this.navList[i+1]&&this.navList[i+1].element.getBoundingClientRect().top>300){
this.currentTitle=this.navList[i].id
break
}
}
标签:const,实现,element,item,titles,文章,id,navList,目录
From: https://www.cnblogs.com/772330747wh/p/17925593.html