The side navigation bar has two functions to achieve:
1. Select any page and scroll to the specified directory location
2. The page content scrolls and the sidebar scrolls along with it
In the page structure part, write a ul > li according to the data loop to generate a side directory
<ul>
<li
v-for="(item, index) in menuArr"
:key="item.id"
:title="item.title"
:class="anchorIdx === index ? 'anchor_current' : '' "
@click="chooseMenu(item, index)"
>
{
{item.title}}
</li>
</ul>
To solve the first requirement, click on any catalog page to scroll to the corresponding content
chooseMenu(item, index) {
//保留当前点击的序列号,服务于选中样式
this.anchorIdx = index
//找到页面包裹每一章内容的节点数组
let contentArr = document.getElementsByClassName('content')
//根据点击的idx,找到对应章节,获得距离页面顶部的位置
let num = contentArr[index].offsetTop
//找到包裹内容页面的元素,即你的滚动条元素,如果是body,直接写windows就可以,不用找元素
let view = document.getElementsByClassName('el-dialog__body')[0]
//调用滚动方法
view.scrollTo({ left: 0, top: num })
}
To solve the second requirement, the page scrolls, and the directory follows
When the page is initialized, add a listening event to the content scrolling element, and define a variable scroll to save the current scrolling value
const view = document.getElementsByClassName('el-dialog__body')[0]
view.addEventListener('scroll', this.dataScroll)
dataScroll() {
this.scroll = document.getElementsByClassName('el-dialog__body')[0].scrollTop
},
Because the scrolling needs to change along with it, it is necessary to monitor the scroll changes in real time in the watch. When a change occurs, judge which chapter is the closest to the top, get the index, and change the selected style of the side directory bar to the corresponding one.
// 找到侧边栏所有元素
let $navs = $('.anchor ul li')
// 找到页面所有章节内容元素
let contentArr = document.getElementsByClassName('content')
for (let i = contentArr.length - 1; i >= 0; i--) {
if (this.scroll >= contentArr[i].offsetTop - 100) {
$navs.eq(i).addClass('current').siblings().removeClass('current ')
break
}
}