vue实现滚动监听,根据文章浏览位置,目录高亮相应标题, 左右联动(源码)
<template>
<div class="container">
<div class="wrapper">
<div
class="section"
style="height: 500px; width: 100%"
v-for="(item, index) in list"
:key="index"
:style="{ height: index == 0 ? '1000px' : '500px' }"
>
<div
style="width: 100%; height: 100%; font-size: 30px; text-align: center; font-weight: bold; color: #fff"
:style="{ background: item.backgroundcolor }"
>
{{ item.name }}
</div>
</div>
</div>
<div id="nac" style="height: 500px"></div>
<nav style="position: fixed; right: 30px; top: 300px">
<div style="margin-left: 20px; font-size: 16px">目录</div>
<el-tabs @tab-click="handleClick" v-model="activeName" tab-position="right" style="height: 200px">
<el-tab-pane
:name="'tab' + index"
:class="index == 0 ? 'current' : ''"
v-for="(item, index) in list"
:key="index"
:label="item.name"
></el-tab-pane>
</el-tabs>
</nav>
</div>
</template>
<script>
export default {
data() {
return {
activeName: "tab0",
scroll: "",
list: [
{
name: "第一条",
backgroundcolor: "#90B2A3",
},
{
name: "第二条",
backgroundcolor: "#A593B2",
},
{
name: "第三条",
backgroundcolor: "#A7B293",
},
{
name: "第四条",
backgroundcolor: "#0F2798",
},
{
name: "第五条",
backgroundcolor: "#0A464D",
},
],
};
},
methods: {
handleClick(tab, event) {
console.log(tab.index);
this.jump(tab.index);
},
dataScroll() {
this.scroll = document.documentElement.scrollTop || document.body.scrollTop;
},
jump(index) {
let jump = document.getElementsByClassName("section");
let total = jump[index].offsetTop;
document.body.scrollTop = total;
document.documentElement.scrollTop = total;
window.pageYOffset = total;
},
loadScroll() {
var self = this;
var sections = document.getElementsByClassName("section");
for (var i = sections.length - 1; i >= 0; i--) {
if (self.scroll >= sections[i].offsetTop - 100) {
self.activeName = "tab" + i;
break;
}
}
},
},
watch: {
scroll: {
handler(newVal, oldVal) {
this.loadScroll();
},
immediate: true,
deep: true,
},
},
mounted() {
window.addEventListener("scroll", this.dataScroll);
},
};
</script>
<style lang="scss" scoped>
* {
padding: 0;
margin: 0;
}
.current {
color: #0578fc !important;
cursor: pointer;
}
nav {
a {
border-left: 3px solid #0177ff;
}
}
</style>
<style>
.el-tabs__header.is-right {
margin-right: 100px !important;
}
</style>