当前位置:首页 > VUE

vue实现滑动高亮

2026-02-17 09:36:35VUE

Vue 实现滑动高亮的方法

使用滚动事件监听和动态类绑定

在Vue中实现滑动高亮可以通过监听滚动事件,结合动态类绑定来实现。以下是一个完整的实现示例:

vue实现滑动高亮

<template>
  <div>
    <div 
      v-for="(item, index) in items" 
      :key="index" 
      :ref="`section-${index}`"
      :class="{ 'highlight': activeIndex === index }"
      class="content-section"
    >
      {{ item }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: ['Section 1', 'Section 2', 'Section 3', 'Section 4'],
      activeIndex: 0,
      sectionOffsets: []
    }
  },
  mounted() {
    this.calculateOffsets()
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    calculateOffsets() {
      this.sectionOffsets = this.items.map((_, index) => {
        return this.$refs[`section-${index}`][0].offsetTop
      })
    },
    handleScroll() {
      const scrollPosition = window.scrollY + 100 // 100px偏移量
      this.sectionOffsets.forEach((offset, index) => {
        const nextOffset = this.sectionOffsets[index + 1] || Infinity
        if (scrollPosition >= offset && scrollPosition < nextOffset) {
          this.activeIndex = index
        }
      })
    }
  }
}
</script>

<style>
.content-section {
  height: 500px;
  margin-bottom: 20px;
  transition: background-color 0.3s;
}
.highlight {
  background-color: #ffeb3b;
}
</style>

使用Intersection Observer API

Intersection Observer API提供了更高效的元素可见性检测方法:

vue实现滑动高亮

<template>
  <div>
    <div 
      v-for="(item, index) in items" 
      :key="index" 
      :ref="`section-${index}`"
      :class="{ 'highlight': activeIndex === index }"
      class="content-section"
    >
      {{ item }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: ['Section 1', 'Section 2', 'Section 3', 'Section 4'],
      activeIndex: 0,
      observer: null
    }
  },
  mounted() {
    this.initObserver()
  },
  beforeDestroy() {
    if (this.observer) {
      this.observer.disconnect()
    }
  },
  methods: {
    initObserver() {
      const options = {
        root: null,
        rootMargin: '0px',
        threshold: 0.5
      }

      this.observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            const index = this.items.findIndex(
              (_, i) => this.$refs[`section-${i}`][0] === entry.target
            )
            if (index !== -1) {
              this.activeIndex = index
            }
          }
        })
      }, options)

      this.items.forEach((_, index) => {
        this.observer.observe(this.$refs[`section-${index}`][0])
      })
    }
  }
}
</script>

结合Vue Router实现路由高亮

如果内容对应不同路由,可以结合Vue Router实现:

<template>
  <div>
    <nav>
      <router-link 
        v-for="(item, index) in items" 
        :key="index" 
        :to="`/section/${index}`"
        :class="{ 'active': $route.params.id == index }"
      >
        {{ item }}
      </router-link>
    </nav>

    <div 
      v-for="(item, index) in items" 
      :key="index" 
      :id="`section-${index}`"
      class="content-section"
    >
      {{ item }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: ['Section 1', 'Section 2', 'Section 3', 'Section 4']
    }
  },
  watch: {
    '$route'(to) {
      if (to.params.id) {
        const element = document.getElementById(`section-${to.params.id}`)
        if (element) {
          element.scrollIntoView({ behavior: 'smooth' })
        }
      }
    }
  }
}
</script>

<style>
.active {
  color: #42b983;
  font-weight: bold;
}
</style>

使用第三方库vue-scrollactive

对于更复杂的需求,可以使用专门为Vue设计的滚动高亮库:

<template>
  <scrollactive class="my-nav">
    <a href="#section1" class="scrollactive-item">Section 1</a>
    <a href="#section2" class="scrollactive-item">Section 2</a>
    <a href="#section3" class="scrollactive-item">Section 3</a>
  </scrollactive>

  <div id="section1" class="section">...</div>
  <div id="section2" class="section">...</div>
  <div id="section3" class="section">...</div>
</template>

<script>
import Vue from 'vue'
import Scrollactive from 'vue-scrollactive'

export default {
  components: { Scrollactive }
}
</script>

<style>
.scrollactive-item.is-active {
  color: #42b983;
}
</style>

以上方法提供了从简单到复杂的多种实现方案,可以根据具体项目需求选择最适合的方式。

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

相关文章

vue实现自定义登录

vue实现自定义登录

实现自定义登录的基本步骤 在Vue中实现自定义登录功能通常需要结合前端和后端技术。以下是一个基本的实现流程: 创建登录表单组件 使用Vue的单文件组件创建一个登录表单,包含用户名和密码输入框以及提…

vue实现递归

vue实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据(如菜单、评论列表、文件目录等)。以下是具体实现方法: 定义递归组件 通过 name 选项让组件可以递归调用自身:…

vue slot实现

vue slot实现

vue slot 的实现方法 在 Vue 中,slot 是一种内容分发机制,允许父组件向子组件传递模板内容。以下是几种常见的 slot 实现方式: 默认 slot 默认 slot 是最基础的 sl…

vue实现建模

vue实现建模

Vue 实现建模的方法 在 Vue 中实现建模通常涉及数据绑定、组件化和状态管理。以下是几种常见的方法: 数据驱动建模 Vue 的核心是数据驱动视图。通过定义数据模型,Vue 会自动更新 DOM。例…

vue实现标题

vue实现标题

Vue 实现标题的方法 在Vue中实现标题可以通过多种方式,以下是几种常见的方法: 方法一:使用模板语法 在Vue组件的模板中直接使用HTML的<h1>到<h6>标签来…

vue实现网站

vue实现网站

Vue 实现网站的基本步骤 Vue.js 是一个渐进式 JavaScript 框架,适合构建现代化的单页应用(SPA)或动态网站。以下是使用 Vue 实现网站的基本方法。 初始化 Vue 项目 使…