当前位置:首页 > VUE

vue实现滑动高亮

2026-03-08 21:56:15VUE

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;
}

响应式处理

在移动端或不同屏幕尺寸下,可能需要调整偏移量或高亮逻辑,通过监听窗口大小变化动态更新计算参数。

vue实现滑动高亮

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

标签: vue高亮
分享给朋友:

相关文章

vue实现右下角弹框

vue实现右下角弹框

实现右下角弹框的基本思路 在Vue中实现右下角弹框,通常需要结合CSS定位和Vue的组件化特性。弹框可以通过绝对定位固定在右下角,并通过Vue控制其显示与隐藏。 创建弹框组件 新建一个Vue组件(如…

vue实现跑车

vue实现跑车

Vue 实现跑车动画效果 使用 Vue 结合 CSS 动画可以实现跑车在屏幕上移动的效果。以下是一个完整的实现方案: 创建 Vue 组件结构 <template> <div c…

vue实现switch

vue实现switch

Vue 实现 Switch 开关组件 在 Vue 中实现 Switch 开关组件可以通过自定义组件或使用现有 UI 库完成。以下是几种常见实现方式: 自定义 Switch 组件 创建一个基础 Sw…

vue实现键盘

vue实现键盘

Vue 实现键盘功能 在Vue中实现键盘功能通常涉及监听键盘事件、处理输入以及渲染虚拟键盘界面。以下是几种常见的实现方式: 监听键盘事件 通过@keydown或@keyup指令监听键盘事件,适用于需…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

vue实现烟花

vue实现烟花

Vue 实现烟花效果 在 Vue 中实现烟花效果可以通过结合 CSS 动画和 JavaScript 动态生成烟花元素。以下是具体实现方法: 动态生成烟花元素 通过 Vue 的 v-for 动态生成烟…