I am a beginner in programming. I would like to ask if I write a music player that I want to be able to click to play and click again to mute. How should I write it? I
have tried several times and failed.
PS. Because I don’t know how to put the music file on the Internet, the current music file is invalid, it is purely indicative.
//關閉
let tag = true;
let music = document.querySelector('#music');
let btn = document.querySelector(".btn");
btn.addEventListener("click", function () {
// 如果目前 flag 不是關閉就撥放
if (tag) {
// music.pause();
music.setAttribute("muted","true");
btn.setAttribute("class", "pause");
tag = false;
} else {
music.play();
btn.setAttribute("class", "play");
tag = true;
}
});
body{
height: 500vh;
}
.btn {
width: 60px;
height: 60px;
background-image: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmxXsF6UrJ0o-wcYdmXOqSpxZXhMzgcCzyAA&usqp=CAU');
background-size: cover;
}
.play{
width: 60px;
height: 60px;
border-radius: 50%;
transition: 1s;
background-image: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmxXsF6UrJ0o-wcYdmXOqSpxZXhMzgcCzyAA&usqp=CAU');
background-size: cover;
}
.pause {
width: 60px;
height: 60px;
border-radius: 50%;
transition: 1s;
background-image: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcScVjEwKCmnfciiCoEZ6am7ZXoIaVR0rUE_O2H1xWkqDMOZV-mk7i8eMwktqV9nHCsyF3A&usqp=CAU');
background-size: cover;
}
<audio id="music" controls="controls">
<source src="demo.mp3" type="audio/mp3">
</audio>
<div class="btn"></div>