文章目录实现

发布时间 2023-12-25 10:31:18作者: 年轻浅识

内容标题绑定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
      }
}