js实现歌词
实现歌词滚动效果
使用HTML和JavaScript实现歌词滚动效果需要结合音频播放器的当前时间与歌词时间轴同步。以下是实现方法:
创建HTML结构包含音频播放器和歌词显示区域:
<audio id="audioPlayer" src="song.mp3"></audio>
<div id="lyricsContainer"></div>
准备歌词数据,通常采用LRC格式的时间标签:

const lyrics = [
{ time: 0.5, text: "第一句歌词" },
{ time: 3.2, text: "第二句歌词" },
{ time: 5.8, text: "第三句歌词" }
// 更多歌词...
];
实现歌词同步逻辑:
const audio = document.getElementById('audioPlayer');
const container = document.getElementById('lyricsContainer');
audio.addEventListener('timeupdate', () => {
const currentTime = audio.currentTime;
let activeIndex = -1;
lyrics.forEach((line, index) => {
if (currentTime >= line.time &&
(index === lyrics.length - 1 || currentTime < lyrics[index + 1].time)) {
activeIndex = index;
}
});
updateLyricsDisplay(activeIndex);
});
function updateLyricsDisplay(activeIndex) {
container.innerHTML = '';
lyrics.forEach((line, index) => {
const p = document.createElement('p');
p.textContent = line.text;
p.className = index === activeIndex ? 'active' : '';
container.appendChild(p);
});
if (activeIndex >= 0) {
const activeLine = container.children[activeIndex];
activeLine.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
添加CSS样式增强视觉效果
为歌词添加基本样式和活动歌词高亮效果:

#lyricsContainer {
height: 300px;
overflow-y: auto;
text-align: center;
font-size: 18px;
line-height: 2;
}
#lyricsContainer p.active {
color: #ff5500;
font-weight: bold;
font-size: 22px;
}
处理动态加载歌词
从LRC文件或API加载歌词数据:
async function loadLyrics(url) {
const response = await fetch(url);
const lrcText = await response.text();
return parseLRC(lrcText);
}
function parseLRC(lrcText) {
const lines = lrcText.split('\n');
const result = [];
lines.forEach(line => {
const timeMatch = line.match(/^\[(\d+):(\d+\.\d+)\]/);
if (timeMatch) {
const minutes = parseFloat(timeMatch[1]);
const seconds = parseFloat(timeMatch[2]);
const time = minutes * 60 + seconds;
const text = line.replace(timeMatch[0], '').trim();
result.push({ time, text });
}
});
return result.sort((a, b) => a.time - b.time);
}
实现歌词搜索功能
为长歌词添加搜索功能:
function searchLyrics(keyword) {
const results = lyrics.filter(line =>
line.text.toLowerCase().includes(keyword.toLowerCase())
);
if (results.length > 0) {
const firstMatchIndex = lyrics.findIndex(line => line === results[0]);
audio.currentTime = lyrics[firstMatchIndex].time - 0.5;
updateLyricsDisplay(firstMatchIndex);
}
}
添加播放控制按钮
扩展播放器控制功能:
document.getElementById('playBtn').addEventListener('click', () => {
audio.play();
});
document.getElementById('pauseBtn').addEventListener('click', () => {
audio.pause();
});
document.getElementById('seekBack').addEventListener('click', () => {
audio.currentTime -= 5;
});
document.getElementById('seekForward').addEventListener('click', () => {
audio.currentTime += 5;
});






