template
<div class="anchor-body">
<div
class="pointer anchor-item"
:class="selectedModuleIndex == index ? 'anchor-item-active ' : ''"
v-for="(item, index) in anchorList"
@click="scrollToAnchor(item)"
>
{{ item.label }}
</div>
</div>
data
selectedModuleIndex: 0,
anchorList: [
{ label: "顶部", value: "top", index: 0 },
{ label: "模块1", value: "modelOne", index: 1 },
{ label: "模块2", value: "modelTwo", index: 2 },
{ label: "模块3", value: "modelThree", index: 3 },
{ label: "模块4", value: "modelFour", index: 4 },
{ label: "模块5", value: "modelFive", index: 5 },
],
生命周期
mounted() {
document
.getElementById("滚动的页面元素的ID")
.addEventListener("scroll", this.handleScroll);
// 默认选中top
this.selectedModuleIndex = 0;
},
beforeDestroy() {
document
.getElementById("bodyRight")
.removeEventListener("scroll", this.handleScroll);
},
methods
handleScroll(e) {
const scrollPosition = e.target.scrollTop;
let selectedIndex = this.selectedModuleIndex;
const moduleTopList = this.anchorList.map((i) => {
i.offsetTop = this.$refs[i.value].offsetTop;
return i;
});
selectedIndex = moduleTopList.find(
(i) => i.offsetTop >= scrollPosition
).index;
this.selectedModuleIndex = selectedIndex;
},
style
.anchor-body {
color: black;
font-size: 1rem;
z-index: 9;
position: fixed;
bottom: 50px;
right: 80px;
background: rgba(0, 0, 0, 0.3);
padding: 1.25rem;
}
.anchor-item {
line-height: 1.75rem;
}
.anchor-item-active,
.anchor-item:hover {
color: blue;
font-weight: bold;
}