首页 > 解决方案 > 我的音乐重叠如何在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(); 
        }
     });
    });
});

标签: javascript

解决方案


单击按钮时,如果歌曲处于暂停状态,请播放它...但您还需要确保所有其他歌曲都已暂停。

您只需要一个额外的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>


推荐阅读