当前位置:首页 > 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实现双折线图

实现双折线图的步骤 安装必要的依赖库(如 ECharts 或 Chart.js),这里以 ECharts 为例: npm install echarts --save 在 Vue 组件中引入 EC…

vue实现vnc

vue实现vnc

Vue 实现 VNC 客户端 在 Vue 项目中实现 VNC 客户端功能,可以通过集成现有的 VNC 客户端库或组件完成。以下是具体实现方法: 安装依赖库 使用 noVNC 或其他 VNC 客…

vue 实现表单

vue 实现表单

Vue 表单实现方法 Vue.js 提供了多种方式实现表单,包括双向数据绑定、表单验证和动态表单生成。以下是常见的实现方法: 基础表单绑定 使用 v-model 指令实现表单元素与数据的双向绑定:…

vue实现ppt

vue实现ppt

Vue 实现 PPT 的功能 Vue 可以结合第三方库或自定义组件实现类似 PPT 的演示效果。以下是几种常见的方法: 使用第三方库 reveal.js reveal.js 是一个流行的演示框架,…

vue实现gps

vue实现gps

Vue 中实现 GPS 定位功能 在 Vue 中实现 GPS 定位功能通常依赖于浏览器的 Geolocation API 或第三方地图服务(如高德、百度地图等)。以下是两种常见的实现方式: 使用浏…

vue实现兼容

vue实现兼容

Vue 兼容性实现方案 Vue.js 的兼容性主要涉及对不同浏览器、Vue 版本以及第三方库的支持。以下是常见的兼容性解决方案: 浏览器兼容性 使用 Babel 转换 ES6+ 代码为 ES5 语…