实现原理
获取全部内容节点,对节点进行遍历,将其中的标题节点存入目录列表中
完整范例代码 (以vue为例)
<template> <div style="padding: 20px"> <div class="menuBox"> <p>目录</p> <el-scrollbar ref="scrollMenuRef" class="scrollMenuBox"> <aside v-for="i in menuList" :key="i" v-html="i.title"></aside> </el-scrollbar> </div> <div class="contentBox"> <main v-for="i in Total" :key="i"> <h1>一级标题{{i}}</h1> <p>内容{{i}}</p> <p>内容{{i}}</p> <p>内容{{i}}</p> <p>内容{{i}}</p> <h2>二级标题{{i}}</h2> <p>内容{{i}}</p> <p>内容{{i}}</p> <p>内容{{i}}</p> <p>内容{{i}}</p> </main> </div> </div> </template> <script> export default { data() { return { menuList: [], Total: 60 } }, mounted() { [...document.getElementsByTagName("main")] .forEach(item => { [...item.children].forEach( item2 => { if (item2.tagName === "H1") { this.menuList.push( { content: item2.innerText, title: item2.outerHTML, level: 1, offsetTop: item2.offsetTop } ) } if (item2.tagName === "H2") { this.menuList.push( { content: item2.innerText, title: item2.outerHTML, level: 2, offsetTop: item2.offsetTop } ) } if (item2.tagName === "H3") { this.menuList.push( { content: item2.innerText, title: item2.outerHTML, level: 3, offsetTop: item2.offsetTop } ) } if (item2.tagName === "H4") { this.menuList.push( { content: item2.innerText, title: item2.outerHTML, level: 4, offsetTop: item2.offsetTop } ) } if (item2.tagName === "H5") { this.menuList.push( { content: item2.innerText, title: item2.outerHTML, level: 5, offsetTop: item2.offsetTop } ) } if (item2.tagName === "H6") { this.menuList.push( { content: item2.innerText, title: item2.outerHTML, level: 6, offsetTop: item2.offsetTop } ) } } ) }) }, } </script> <style scoped> /*目录悬浮*/ .menuBox { position: fixed; } /*内容居中*/ .contentBox { width: 60%; margin: auto; } /*el-scrollbar 必须指定高度*/ .scrollMenuBox { height: 600px; width: 200px; } /*隐藏水平滚动条*/ /deep/ .el-scrollbar__wrap { overflow-x: hidden; } </style>
最终效果