vue实现滑动高亮
Vue 实现滑动高亮的方法
使用滚动事件监听
通过监听滚动事件,计算当前视口位置与元素位置的相对关系,动态添加高亮样式。
// 在mounted钩子中监听滚动
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
// 在beforeDestroy钩子中移除监听
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
const sections = document.querySelectorAll('.section')
let current = ''
sections.forEach(section => {
const sectionTop = section.offsetTop
const sectionHeight = section.clientHeight
if (pageYOffset >= sectionTop - sectionHeight / 3) {
current = section.getAttribute('id')
}
})
this.activeSection = current
}
}
使用 Intersection Observer API
更高效的实现方式,利用现代浏览器提供的交叉观察器API。
data() {
return {
observer: null,
activeSection: ''
}
},
mounted() {
this.observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.activeSection = entry.target.id
}
})
}, {
threshold: 0.5
})
document.querySelectorAll('.section').forEach(section => {
this.observer.observe(section)
})
},
beforeDestroy() {
this.observer.disconnect()
}
样式绑定
在模板中使用动态类绑定实现高亮效果。
<template>
<div
v-for="section in sections"
:id="section.id"
class="section"
:class="{ 'active': activeSection === section.id }"
>
{{ section.content }}
</div>
</template>
<style>
.section {
padding: 100px 0;
transition: all 0.3s ease;
}
.section.active {
background: rgba(0, 150, 255, 0.1);
border-left: 4px solid #0096ff;
}
</style>
优化性能
对于大型应用,可以添加防抖函数减少滚动事件触发频率。
methods: {
handleScroll: _.debounce(function() {
// 滚动处理逻辑
}, 100)
}
导航菜单联动
实现导航菜单与内容区域的联动高亮。
<template>
<nav>
<a
v-for="link in links"
:href="`#${link.id}`"
:class="{ 'active': activeSection === link.id }"
>
{{ link.text }}
</a>
</nav>
</template>
这些方法可以根据具体需求组合使用,实现流畅的滑动高亮效果。







