vue中 tab锚点联动 代码
<template>
<div class="scrollDemo">
<div class="demoNav flex-center-center">
<div
class="demoNavItem"
v-for="(item, index) in demoNavItem"
:key="index"
:class="{ navActive: idx == index }"
@click="changNav(index)"
>
{{ item }}
</div>
</div>
<div class="demoContent">
<!-- 如果内容为循环,id则定义为:id="'demoItem'+index" -->
<div
:class="'demoItem demoItem' + index"
:id="'demoItem' + index"
:key="index + '_'"
v-for="(item, index) in demoNavItem"
>
{{ item }}
</div>
</div>
</div>
</template>
<script>
// 引入
var VueScrollTo = require("vue-scrollto");
export default {
data() {
return {
idx: 0,
scroll: null,
demoNavItem: [
"谷歌浏览器",
"uc浏览器",
"IE浏览器",
"火狐浏览器",
"360浏览器",
"猎豹浏览器",
],
};
},
mounted() {
// scroll代表滚动条距离页面顶部距离
window.addEventListener("scroll", this.dataScroll);
},
watch: {
//监听scroll变量,只要滚动条位置变化就会执行方法loadScroll
scroll: function () {
this.loadScroll();
},
},
methods: {
// 导航选中效果
changNav(index) {
this.idx = index;
VueScrollTo.scrollTo(document.getElementById("demoItem" + index), 300, {
offset: -50,
});
},
// 用循环的方式将每个标题离顶部的距离与滚动条当前位置对比来确定哪个标题需要变为高亮
loadScroll: function () {
var self = this;
var sections = document.getElementsByClassName("demoItem");
for (var i = sections.length - 1; i >= 0; i--) {
if (self.scroll >= sections[i].offsetTop - 100) {
//我在上面规定了每个el-tab-pane标签的name属性值为tab+该标签的index值
self.idx = i;
break;
}
}
},
dataScroll: function () {
this.scroll =
document.documentElement.scrollTop || document.body.scrollTop;
},
},
};
</script>
<style scoped>
.flex-center-center {
display: flex;
align-items: center;
justify-content: center;
}
.demoNav {
width: 100%;
height: 70px;
background: rgba(0, 31, 144, 1);
position: sticky;
left: 0;
top: 0;
}
.demoNavItem {
font-size: 40px;
color: #fff;
margin-left: 30px;
cursor: pointer;
}
.navActive {
color: red;
}
.demoItem {
width: 100%;
height: 600px;
font-size: 60px;
color: #fff;
text-align: center;
padding: 60px 0 0 0;
}
.demoItem0 {
background: gold;
}
.demoItem1 {
background: red;
}
.demoItem2 {
background: chartreuse;
}
.demoItem3 {
background: cornflowerblue;
}
.demoItem4 {
background: cyan;
}
.demoItem5 {
background: darkmagenta;
}
</style>
入代码片