我还是个新手我正在学习,
帮助,如果你可以我不明白,我想添加2 3首歌曲的网站,我写的代码,但只有1首歌的作品如何让所有的歌曲都播放但不是同时,而是依次,
例如我正在听音乐1,然后我想听播放2,当我按播放2,播放1应该停止我不明白怎么做,你能提前帮帮忙吗,谢谢我将保留代码
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>
您需要唯一的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>