vue之 点击标题滚动到对应位置 + 滚动影响上面的高亮
NavBar.vue
<template>
<div class="nav_bar">
<div class="left">
<slot name="left">left</slot>
</div>
<div class="center">
<slot name="center">center</slot>
</div>
<div class="right">
<slot name="right">right</slot>
</div>
</div>
</template>
<script>
export default {
name: "",
data() {
return {};
},
components: {}
};
</script>
<style lang="scss" scoped>
.nav_bar {
display: flex;
position: fixed;
top: 0;
left: 0;
height: 44px;
width: 100%;
line-height: 44px;
text-align: center;
background: #fff;
.left,
.right {
width: 44px;
height: 100%;
}
.center {
flex: 1;
height: 100%;
}
}
</style>
Home.vue
<template>
<div class="group_business">
<NavBar>
<div slot="center" class="navbar_c">
<div
v-for="(item, index) in titles"
:key="item"
@click="itemClick(index)"
:class="moveIndex === index ? 'active' : ''"
>{{ item }}</div>
</div>
</NavBar>
<div class="group_business_con">
<div class="floor_con" ref="floor_con">
<div id="floor0">商品</div>
<div id="floor1">参数</div>
<div id="floor2">评论</div>
<div id="floor3">推荐</div>
</div>
</div>
</div>
</template>
<script>
import NavBar from "./NavBar";
export default {
name: "Qa",
components: { NavBar },
data() {
return {
moveIndex: 0,
titles: ["商品", "参数", "评论", "推荐"]
};
},
mounted() {
window.addEventListener("scroll", this.handleScroll, true);
},
methods: {
itemClick(index) {
this.moveIndex = index;
let PageId = document.querySelector("#floor" + index);
window.scrollTo({
top: PageId.offsetTop - 40,
behavior: "smooth"
});
},
handleScroll() {
this.scrollY = document.documentElement.scrollTop + 40;
let floorCon = this.$refs.floor_con;
let floorCon = this.$refs.floor_con;
let floorList,floor_0,floor_1,floor_2,floor_3;
if (floorCon) {
floorList = floorCon.querySelectorAll("div");
floor_0 = floorList[0].offsetTop;
floor_1 = floorList[1].offsetTop;
floor_2 = floorList[2].offsetTop;
floor_3 = floorList[3].offsetTop;
}
if (this.scrollY) {
if (floor_0 <= this.scrollY && this.scrollY < floor_1) {
this.moveIndex = 0;
return false;
} else if (floor_1 <= this.scrollY && this.scrollY < floor_2) {
this.moveIndex = 1;
return false;
} else if (floor_2 <= this.scrollY && this.scrollY < floor_3) {
this.moveIndex = 2;
return false;
} else if (this.scrollY >= floor_3) {
this.moveIndex = 3;
return false;
}
}
}
}
};
</script>
<style lang="scss" scoped>
.group_business {
display: flex;
flex-direction: column;
.navbar_c {
display: flex;
justify-content: space-around;
align-items: center;
}
.group_business_con {
flex: 1;
margin: 44px 0 49px 0;
}
.active {
color: red;
}
.floor_con {
div {
font-size: 30px;
color: #fff;
text-align: center;
height: 600px;
&:nth-of-type(1) {
background: pink;
}
&:nth-of-type(2) {
background: yellow;
}
&:nth-of-type(3) {
background: red;
}
&:nth-of-type(4) {
background: orange;
}
}
}
}
</style>