vue歌词滚动实现
实现 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;
}
完整组件示例
<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>






