当前位置:首页 > 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 中实现点击样式可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-bind:class 动态绑定类名 通过数据驱动的方式动态切换类名,结合 CS…

vue实现年历

vue实现年历

Vue 实现年历的方法 使用 Vue 实现年历可以通过组件化开发方式,结合日期计算和动态渲染完成。以下是两种常见的实现方式: 基于原生 Vue 的日历组件 创建 Calendar.vue 组件文件…

vue实现多级弹窗

vue实现多级弹窗

Vue 多级弹窗实现方法 方法一:使用动态组件与递归组件 在 Vue 中可以通过动态组件配合递归组件实现多级弹窗。定义一个基础弹窗组件,通过递归调用自身实现层级嵌套。 基础弹窗组件模板示例:…

vue实现屏幕共享

vue实现屏幕共享

Vue 实现屏幕共享的方法 使用 WebRTC 和 getDisplayMedia API 通过 navigator.mediaDevices.getDisplayMedia 捕获屏幕内容,结合 We…

vue前端实现注册

vue前端实现注册

使用 Vue 实现用户注册功能 环境准备 确保已安装 Vue CLI 或通过 CDN 引入 Vue。若使用 Vue CLI,需安装 axios 或其他 HTTP 库用于后端通信。 注册表单组件 创建…

vue前端实现搜索

vue前端实现搜索

实现搜索功能的基本方法 在Vue中实现搜索功能通常涉及以下几个关键步骤,结合数据绑定、计算属性和方法调用来动态过滤和显示结果。 数据绑定与输入处理 使用v-model双向绑定搜索输入框的值,监听用…