我的音乐重叠如何在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>

最新更新