如果我用这个${music.lyric}来获取歌词怎么修改?
时间: 2024-03-15 20:46:46 浏览: 23
如果你想通过 `${music.lyric}` 来获取歌词并实现歌词滚动,可以将 HTML 模板中的歌词部分修改成以下代码:
```html
<div id="lyrics">
<!-- 使用模板语法获取歌词 -->
<p v-for="(line, index) in music.lyric.split('\n')" :key="index">{{ line }}</p>
</div>
```
在这个代码中,我们使用了 Vue.js 的模板语法 `v-for` 来遍历歌词文本中的每一行,并将它们分别显示在一个 `p` 元素中。由于歌词文本中的每一行都是以换行符 `\n` 分隔的,因此我们使用 `split('\n')` 方法将歌词文本分割成一个行数组,然后再通过 `v-for` 遍历这个数组,并将每一行渲染成一个 `p` 元素。这个代码还使用了 `:key="index"` 来指定每个 `p` 元素的唯一标识,以提高渲染性能。
当你需要动态更新歌词时,可以通过 JavaScript 来修改 `music.lyric` 的值,然后 Vue.js 会自动重新渲染歌词部分。例如,你可以在播放器的 `timeupdate` 事件处理函数中,根据当前播放时间动态显示对应的歌词行:
```js
player.addEventListener('timeupdate', function() {
// 计算当前播放时间对应的歌词行
var currentTime = this.currentTime;
var lines = music.lyric.split('\n');
for (var i = 0; i < lines.length; i++) {
var match = lines[i].match(/^\[(\d{2}):(\d{2})\.(\d{2})\](.*)$/);
if (match && match[1] && match[2] && match[3] && match[4]) {
var time = parseInt(match[1]) * 60 + parseInt(match[2]) + parseInt(match[3]) / 100;
if (currentTime >= time && (!lines[i + 1] || currentTime < parseInt(lines[i + 1].match(/^\[(\d{2}):(\d{2})\.(\d{2})\]/)[1]) * 60 + parseInt(lines[i + 1].match(/^\[(\d{2}):(\d{2})\.(\d{2})\]/)[2]) + parseInt(lines[i + 1].match(/^\[(\d{2}):(\d{2})\.(\d{2})\]/)[3]) / 100)) {
// 当前播放时间对应的歌词行
var currentLine = i;
break;
}
}
}
// 滚动到当前歌词行
var lyrics = document.querySelector('#lyrics');
var currentElement = lyrics.querySelectorAll('p')[currentLine];
if (currentElement) {
lyrics.scrollTop = currentElement.offsetTop - lyrics.offsetTop;
}
});
```
在这个代码中,我们监听播放器的 `timeupdate` 事件,然后根据当前播放时间计算出对应的歌词行。具体地,我们首先将歌词文本分割成行数组,并使用正则表达式 `^\[(\d{2}):(\d{2})\.(\d{2})\](.*)$` 匹配每一行的时间标记和歌词文本,如果匹配成功,则将时间标记解析成秒数,并判断当前播放时间是否在该行和下一行之间。如果当前播放时间对应的歌词行发生变化,我们就将滚动条滚动到该行,以便用户看到当前播放的歌词。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)