当前位置:首页 > 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实现https

vue实现https

Vue 中实现 HTTPS 的步骤 在 Vue 项目中实现 HTTPS 主要涉及开发环境配置和生产环境部署。以下是具体方法: 开发环境配置(Vue CLI 或 Vite) 使用 mkcert 生成…

vue的实现

vue的实现

Vue 的实现原理 Vue 是一个渐进式 JavaScript 框架,其核心实现主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是 Vue 实现的主要技术细节。 响应式系统 Vue 的响…

vue实现定位

vue实现定位

Vue 中实现定位的方法 在 Vue 中实现定位可以通过以下几种方式: 使用 CSS 定位 通过 CSS 的 position 属性实现定位,Vue 中可以直接在组件的 <style>…

vue实现frame

vue实现frame

Vue 中实现 iframe 的方法 在 Vue 中可以通过直接使用 <iframe> 标签或动态绑定 src 属性来实现 iframe 功能。 基本用法 <template&g…

vue代理实现

vue代理实现

Vue 代理实现方法 在 Vue 项目中,配置代理可以解决开发环境下的跨域问题,通常通过修改 vue.config.js 文件实现。以下是几种常见的代理配置方式: 基础代理配置 在 vue.conf…

利用vue 实现

利用vue 实现

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