当前位置:首页 > VUE

vue歌词滚动实现

2026-01-08 06:22:41VUE

实现 Vue 歌词滚动的核心方法

监听当前播放时间 通过 audio 元素的 timeupdate 事件获取当前播放时间,并与歌词时间戳对比。在 Vue 中使用 @timeupdate 绑定事件:

<audio ref="audio" @timeupdate="handleTimeUpdate"></audio>

methods: {
  handleTimeUpdate() {
    const currentTime = this.$refs.audio.currentTime;
    this.updateLyric(currentTime);
  }
}

解析歌词文件 歌词通常为 LRC 格式,需解析成结构化数据。使用正则表达式分割每行歌词:

parseLyric(lrcText) {
  const lines = lrcText.split('\n');
  return lines.map(line => {
    const timeReg = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/;
    const result = timeReg.exec(line);
    if (!result) return null;

    const min = parseInt(result[1]) * 60;
    const sec = parseInt(result[2]);
    const ms = parseInt(result[3]) / 1000;
    return {
      time: min + sec + ms,
      text: line.replace(timeReg, '').trim()
    };
  }).filter(item => item);
}

动态高亮当前行 通过 CSS 类绑定实现高亮效果,结合计算属性确定当前行索引:

computed: {
  currentLineIndex() {
    return this.lyrics.findIndex((line, index) => {
      const nextLine = this.lyrics[index + 1];
      return this.currentTime >= line.time && 
             (!nextLine || this.currentTime < nextLine.time);
    });
  }
}

平滑滚动效果 使用 CSS transform 和过渡动画实现滚动,通过动态计算偏移量:

.lyric-container {
  transition: transform 0.3s ease;
}
.active-line {
  color: #ff0000;
  font-weight: bold;
}

性能优化建议 对于长歌词列表,使用虚拟滚动技术(如 vue-virtual-scroller)。避免频繁 DOM 操作,采用 CSS will-change 属性提升渲染性能:

.lyric-line {
  will-change: transform;
}

完整组件示例

vue歌词滚动实现

<template>
  <div class="lyric-wrapper">
    <div 
      class="lyric-container"
      :style="{ transform: `translateY(${-currentLineIndex * lineHeight}px)` }"
    >
      <div 
        v-for="(line, index) in lyrics"
        :key="index"
        :class="{ 'active-line': index === currentLineIndex }"
        class="lyric-line"
      >
        {{ line.text }}
      </div>
    </div>
  </div>
</template>

标签: 歌词vue
分享给朋友:

相关文章

vue实现心电图

vue实现心电图

Vue 实现心电图效果 在 Vue 中实现心电图效果通常需要结合 Canvas 或 SVG 进行动态绘图,模拟心电图数据的实时变化。以下是两种实现方式的核心思路和代码示例: 使用 Canvas 绘制…

vue 实现 confirm

vue 实现 confirm

实现确认对话框的方法 在Vue中实现确认对话框可以通过多种方式完成,包括使用内置组件、第三方库或自定义组件。 使用浏览器原生confirm 最简单的实现方式是直接调用浏览器原生的confirm方法。…

vue实现首页

vue实现首页

Vue 实现首页的基本步骤 安装 Vue.js 和相关依赖,可以通过 Vue CLI 或 Vite 快速初始化项目。Vue CLI 适合传统项目,Vite 更适合现代前端开发。 npm instal…

vue实现计数

vue实现计数

Vue 实现计数功能 在 Vue 中实现计数功能可以通过多种方式完成,以下是几种常见的方法: 使用 Vue 数据绑定和事件监听 通过 Vue 的数据绑定和事件监听,可以轻松实现计数功能。以下是一个简…

vue 实现登录验证

vue 实现登录验证

Vue 实现登录验证的方法 使用 Vue Router 进行路由守卫 在 Vue 项目中,可以通过 Vue Router 的路由守卫(Navigation Guards)实现登录验证。路由守卫可以在路…

vue如何实现排序

vue如何实现排序

实现数组排序 在Vue中实现数组排序可以通过computed属性或methods来处理。假设有一个数组items,可以创建一个计算属性返回排序后的数组: data() { return {…