当前位置:首页 > 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 实现挂载的基本方法 在 Vue 中,挂载是将 Vue 实例与 DOM 元素关联的过程。通过挂载,Vue 可以管理 DOM 并实现数据绑定和响应式更新。 创建 Vue 实例并挂载 const…

vue实现颜色

vue实现颜色

Vue 实现颜色的方法 在 Vue 中实现颜色管理可以通过多种方式,以下是一些常见的方法: 使用 CSS 变量动态绑定颜色 在 Vue 组件的样式中定义 CSS 变量,并通过 Vue 的数据绑定动态…

利用vue 实现

利用vue 实现

以下是利用 Vue 实现常见功能的几种方法,分为不同场景和技术要点: 数据绑定与响应式更新 Vue 的核心特性是数据绑定,通过 v-model 实现双向绑定: <template>…

vue实现hovuer

vue实现hovuer

Vue 实现 Hover 效果 在 Vue 中实现 hover 效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 直接控制 通过 :hover 伪类实现,无需额外的 JavaScrip…

vue实现字幕

vue实现字幕

Vue 实现字幕功能 在 Vue 中实现字幕功能可以通过动态绑定数据和 CSS 动画来实现。以下是具体实现方法: 1. 基础字幕组件 创建一个字幕组件,通过 v-model 或 props 接收字…

vue实现settimeout

vue实现settimeout

在 Vue 中实现 setTimeout Vue 中可以通过 JavaScript 原生的 setTimeout 方法实现延时操作,但需要注意结合 Vue 的响应式特性和生命周期管理。以下是几种常见实…