vue实现滑动高亮
Vue 实现滑动高亮效果
监听滚动事件
通过 window.addEventListener 监听滚动事件,在 Vue 组件的 mounted 生命周期钩子中添加事件监听器,在 beforeDestroy 钩子中移除监听器以避免内存泄漏。
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}
计算元素位置
获取需要高亮的元素列表,通过 getBoundingClientRect() 方法计算每个元素相对于视口的位置,判断当前滚动位置是否处于元素范围内。
handleScroll() {
const sections = document.querySelectorAll('.section');
const scrollPosition = window.scrollY + 100; // 偏移量可调整
sections.forEach(section => {
const top = section.offsetTop;
const height = section.offsetHeight;
if (scrollPosition >= top && scrollPosition < top + height) {
this.currentSection = section.id;
}
});
}
动态绑定高亮样式
使用 Vue 的动态 class 绑定功能,根据当前激活的段落 ID 添加高亮样式。
<template>
<div
v-for="section in sections"
:id="section.id"
:class="{ 'active': currentSection === section.id }"
class="section"
>
{{ section.content }}
</div>
</template>
<style>
.section {
padding: 20px;
transition: background 0.3s;
}
.section.active {
background-color: #f0f8ff;
}
</style>
优化性能
使用节流函数(throttle)限制滚动事件的触发频率,避免频繁计算导致性能问题。
import { throttle } from 'lodash';
methods: {
handleScroll: throttle(function() {
// 计算逻辑
}, 100)
}
平滑滚动支持
通过 scrollIntoView 或 CSS 的 scroll-behavior 属性实现平滑滚动效果,提升用户体验。
html {
scroll-behavior: smooth;
}
响应式处理
在移动端或不同屏幕尺寸下,可能需要调整偏移量或高亮逻辑,通过监听窗口大小变化动态更新计算参数。

data() {
return {
offset: 100,
};
},
created() {
window.addEventListener('resize', this.updateOffset);
},
methods: {
updateOffset() {
this.offset = window.innerWidth < 768 ? 50 : 100;
}
}






