首页 > 解决方案 > how to add 2 3 songs to website using html javascript

问题描述

I am still newbie I'm studying,

help if you can I don't understand, I want to add 2 3 songs to the site I wrote the code but only 1 song works how to make all songs play but not simultaneously, but in turn,

For example I am listening to music 1 and then I want to listen to play 2, when I press play 2, play 1 should stop how to do it i don't understand can you help in advance thanks I'll leave the code

var mySong = document.getElementById("mySong");
var icon = document.getElementById("icon");

icon.onclick = function() {
  if(mySong.paused){
      mySong.play();
      icon.src = "img/pause-icon.png";
  }else{
    mySong.pause();
    icon.src = "img/play-icon.jpg";
  }
}
<img src="img/play-icon.jpg" alt="" id="icon" width="80">

          <audio id="mySong">
            <source src="Ганвест - Кайфули.mp3" type="audio/mp3">
          </audio>

          <img src="img/play-icon.jpg" alt="" id="icon" width="80">

          <audio id="mySong">
            <source src="Ганвест - Кайфули.mp3" type="audio/mp3">
          </audio>

标签: javascripthtml

解决方案


您需要唯一的 ID 或委托,然后您根本不需要 ID:

注意我将图标 id 更改为图标类,将每首歌曲包装在一个 div 中,并将所有歌曲也包装在一个 div 中

const icons = {
  play: "https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/video-play.png",
  pause: "https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/play-pause.png"
}
const isPlaying = audioElement => !audioElement.paused;

const container = document.getElementById("songs");
const songs = container.querySelectorAll(".song audio");
const controls = container.querySelectorAll(".song .icon");

container.addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.matches(".icon")) {
    const mySong = tgt.closest(".song").querySelector("audio");
    // pause all other songs
    songs.forEach((song,i) => {
      if (isPlaying(song) && song != mySong) {
        song.pause()
        controls[i].src=icons.play;
      }
    }); 
    if (mySong.paused) {
      mySong.play();
      tgt.src = icons.pause;
    } else {
      mySong.pause();
      tgt.src = icons.play;
    }
  }
})
<div id="songs">
  <div class="song">
    <img src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/video-play.png" alt="Toggle" class="icon" width="80">

    <audio id="mySong1">
      <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" type="audio/mp3"></audio>
  </div>
  <div class="song">
    <img src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-gallery/3.1.1/img/video-play.png" alt="Toggle" class="icon" width="80">

    <audio id="mySong2">
      <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3" type="audio/mp3"></audio>
  </div>
</div>


推荐阅读