HTML5是一種用于構建網頁和網頁應用程序的標準。其中,包含一個能夠實現歌詞滾動的元素,而且這個功能還非常簡單易用。
<audio id="music" src="music.mp3"></audio> <div id="lyrics"></div> <script> var lyric = [ {time: 0, text: "Verse 1: "}, {time: 3, text: "It's been a long day without you my friend "}, {time: 8, text: "And I'll tell you all about it when I see you again "}, {time: 13, text: "We've come a long way from where we began "}, {time: 17, text: "Oh I'll tell you all about it when I see you again "}, {time: 21, text: "When I see you again "}, {time: 25, text: "Damn, who knew "}, ... ]; var index = 0; var lyricContainer = document.getElementById('lyrics'); var audio = document.getElementById('music'); function updateLyric() { var current = lyric[index]; var next = lyric[index+1]; if (audio.currentTime >= current.time) { // Display current lyric lyricContainer.innerHTML = current.text; // Scroll to current lyric lyricContainer.scrollTop = lyricContainer.scrollHeight - lyricContainer.clientHeight; // Move to next lyric index++; } } setInterval(updateLyric, 100); </script>
上述代碼實現了一個歌詞滾動的示例。首先,我們按照時間順序定義了歌詞信息,每條歌詞都包含時間和文本;然后,我們使用一個容器div來顯示歌詞,并添加了一個audio元素來播放音樂。
接著,我們編寫了一個updateLyric函數,它在每100毫秒鐘執行一次,從而實現了歌詞隨著音樂播放而滾動的效果。在該函數中,我們首先獲取當前時間點的歌詞信息,并顯示在容器div中。然后,我們將容器div滾動到最后一行,以便用戶始終能夠看到當前正在播放的歌詞。最后,我們將index加1,以便在下一個時間點顯示下一句歌詞。
以上就是簡單易用的HTML5歌詞滾動代碼。可以在歌詞頁面中使用,讓用戶更好地欣賞歌曲。