javascript - 我的音乐重叠如何在javascript中停止
问题描述
我在javascript中有这段代码..我希望它可以在我的歌曲变量中的每一首歌曲中工作..任何关于如何做到这一点的帮助谢谢
window.addEventListener("load", () => {
let songs = document.querySelectorAll(".song");
let sections = document.querySelectorAll(".section button");
//song start play
sections.forEach((button, index) => {
button.addEventListener("click", function () {
if(songs[index].paused){
songs[index].play();
} else{
songs[index].pause();
}
});
});
});
解决方案
单击按钮时,如果歌曲处于暂停状态,请播放它...但您还需要确保所有其他歌曲都已暂停。
您只需要一个额外的forEach
循环来暂停它们,然后再播放与单击的按钮相关联的循环。
window.addEventListener("load", () => {
let songs = document.querySelectorAll(".song");
let sections = document.querySelectorAll(".section button");
//song start play
sections.forEach((button, index) => {
button.addEventListener("click", function () {
if(songs[index].paused){
songs.forEach(song => song.pause()) // This will pause all songs
songs[index].play();
} else{
songs[index].pause();
}
});
});
});
audio{
display: none;
}
button{
margin: 0.5em;
}
<div class="section">
<audio controls class="song" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"></audio>
<button class="button">Play song #1</button>
</div>
<div class="section">
<audio controls class="song" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"></audio>
<button class="button">Play song #2</button>
</div>
<div class="section">
<audio controls class="song" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3"></audio>
<button class="button">Play song #3</button>
</div>
推荐阅读
- android - 如何异步调用 HTTP Post API?
- .net - GCP: 403 调用者没有权限
- java - 返回两个数组的排序组合
- python - args中的点/空格名-python
- javascript - 如何从 Html 单选按钮获取值
- sql-server - 如何在 Manjaro linux 中配置 SQL Server?
- spring-boot - 如何模拟 Feign 客户端
- java - 程序类型已经存在:com.bumptech.glide.GeneratedAppGlideModule
- snmp - Snmpwalk 随机返回更少的变量(以 SNMPv2-MIB::snmpSetSerialNo.0 结尾)
- scala - 尝试使持久性参与者需要带有 RequiresMessageQueue 的自定义邮箱时出错