当前位置:首页 > 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 格式,需解析成结构化数据。使用正则表达式分割每行歌词:

vue歌词滚动实现

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 和过渡动画实现滚动,通过动态计算偏移量:

vue歌词滚动实现

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

完整组件示例

<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 实现好评弹框可以通过组件化方式完成,结合动态数据绑定和事件处理。以下是具体实现步骤: 1. 创建弹框组件 新建一个 RatingDialog.vue 组件…

vue 动画实现

vue 动画实现

Vue 动画实现方式 Vue 提供了多种方式实现动画效果,主要分为内置组件和第三方库集成。 使用 Vue 内置过渡组件 Vue 的 <transition> 和 <transiti…

vue实现答辩

vue实现答辩

Vue 实现答辩系统的关键步骤 项目初始化与配置 使用 Vue CLI 或 Vite 创建项目,安装 Vue Router 管理路由,Pinia/Vuex 进行状态管理。配置 ESLint 和 Pre…

vue watch实现

vue watch实现

在 Vue 中实现 watch 监听数据变化 Vue 的 watch 选项用于监听数据变化并执行相应的回调函数。以下是几种常见的实现方式: 基础用法 export default { data(…

vue导航实现

vue导航实现

Vue 导航实现方法 在 Vue 中实现导航功能通常涉及路由配置、组件设计和状态管理。以下是几种常见的实现方式: 使用 Vue Router 实现基础导航 安装 Vue Router: npm i…

vue 实现templateurl

vue 实现templateurl

在 Vue 中,templateUrl 是 Angular 中的一个概念,用于指定外部 HTML 文件作为模板。Vue 本身不直接支持 templateUrl,但可以通过以下方法实现类似功能: 使用…