vue鼠标点击标题滚动到指定模块,如果滚动页面到指定模块的话标题同样改变颜色
<script>
export default {
name: 'ceshi',
data() {
return {
activeSection: 0, // 默认激活第一个标题
sections: [
{ title: 'Section 1', content: 'Content for section 1' },
{ title: 'Section 2', content: 'Content for section 2' },
{ title: 'Section 3', content: 'Content for section 3' },
],
};
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
scrollToSection(index) {
const section = this.$refs.sectionsRef[index];
section.scrollIntoView({ behavior: 'smooth' });
this.activeSection = index;
},
handleScroll() {
const sections = this.$refs.sectionsRef;
let currentActiveSection = 0;
sections.forEach((section, index) => {
const sectionTop = section.offsetTop;
if (window.scrollY >= sectionTop - 50) { // 50 是为了调整滚动时的误差
currentActiveSection = index;
}
});
this.activeSection = currentActiveSection;
},
isActiveSection(index) {
return this.activeSection === index;
},
},
}
</script>
<template>
<div id="app">
<div class="nav">
<div
v-for="(section, index) in sections"
:key="index"
class="nav-item"
:class="{ active: isActiveSection(index) }"
@click="scrollToSection(index)"
>
{{ section.title }}
</div>
</div>
<div class="content">
<div
v-for="(section, index) in sections"
:key="index"
:id="'section-' + index"
class="section"
ref="sectionsRef"
>
<h2>{{ section.title }}</h2>
<p>{{ section.content }}</p>
</div>
</div>
</div>
</template>
<style scoped lang="scss">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.nav {
position: fixed;
top: 0;
width: 100%;
background: #fff;
border-bottom: 1px solid #ddd;
display: flex;
justify-content: center;
}
.nav-item {
padding: 15px;
cursor: pointer;
transition: color 0.3s;
}
.nav-item.active {
color: #42b983; /* 改变激活标题的颜色 */
}
.content {
margin-top: 60px; /* 留出导航栏的空间 */
}
.section {
height: 400px; /* 每个模块的高度,可以根据需要调整 */
border-bottom: 1px solid #ddd;
padding: 20px;
box-sizing: border-box;
}
</style>