<template>
<div class="wrap">
<div class="result" @scroll="onScroll">
<div class="scroll-item"><span>第一</span></div>
<div class="scroll-item"><span>第二</span></div>
<div class="scroll-item"><span>第三</span></div>
<div class="scroll-item"><span>第四</span></div>
</div>
<div class="list" ref="header" :class="headerFixed ? 'issFixed' : ''">
<div v-for="(item, index) in title_list" :key="index">
<span
ref="spans"
:style="{ color: activeStep === index ? '#1987e1' : '#000000' }"
@click="jump(index)"
>
{{ item.title }}
</span>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeStep: 0,
title_list: [
{ title: '第一' },
{ title: '第二' },
{ title: '第三' },
{ title: '第四' },
],
// 目录固定吸顶
offsetTop: 0,
offsetHeight: 0,
headerFixed: 0
}
},
methods: {
// 点击事件
jump(index) {
var items = document.querySelectorAll(".scroll-item");
for (var i = 0; i < items.length; i++) {
if (index === i) {
items[i].scrollIntoView({
block: "start",//默认跳转到顶部
behavior: "smooth"//滚动的速度
});
}
}
},
// 滚动行为
onScroll(e) {
let scrollItems = document.querySelectorAll(".scroll-item");
for (let i = scrollItems.length - 1; i >= 0; i--) {
// 判断滚动条滚动距离是否大于当前滚动项可滚动距离
let judge =
e.target.scrollTop >=
scrollItems[i].offsetTop - scrollItems[0].offsetTop;
if (judge) {
this.activeStep = i;
break;
}
}
},
handleScroll() {
// 得到页面滚动的距离,兼容写法
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
// 判断页面滚动的距离是否大于吸顶元素的位置
this.headerFixed = scrollTop > this.offsetTop - this.offsetHeight;
}
},
mounted() {
this.$nextTick(() => {
// 获取吸顶元素的dom
let header = this.$refs.header;
// 吸顶元素到top的距离
this.offsetTop = header.offsetTop;
// 元素自身的高度
this.offsetHeight = header.offsetHeight;
// 监听滚动条
window.addEventListener("scroll", this.handleScroll);
});
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll);
},
}
</script>
<style scoped>
.wrap {
display: flex;
justify-content: space-around;
}
.issFixed {
position: fixed;
top: 0px;
/* left: 0px; */
right: 0px;
z-index: 4;
}
.list {
width: 60px;
line-height: 60px;
background: pink;
}
.result {
width: 100%;
height: 500px;
overflow: scroll;
}
.scroll-item {
width: 100%;
height: 500px;
margin-top: 20px;
background: yellow;
}
.scroll-item > span {
font-size: 40px;
}
.scroll-item:first-child {
margin-top: 0;
}
.scroll-item:last-child {
height: 500px;
}
/* 最后一个元素的最小高度要大于等于父元素的高度,如果scroll-item为高度自适应的话,那么最后一个scroll-item就得设置min-height:100% */
</style>
vue滚动导航菜单
最新推荐文章于 2024-07-03 11:23:19 发布