我正在做一个项目,我试图在导航栏中创建一个音乐按钮。当你点击它时,一首歌播放,再次点击它会暂停它。我试过几个版本,但不知道为什么他们不工作。我在codePen上寻找了一些想法,但还是没有找到。希望有人能帮忙。我设法让它在某个点上工作,但它根本没有暂停,所以我重写了代码。
这是相关的HTML代码:
<ul>
<li class="nav-item nohover">
<audio id="music-button">
<source src="Zara%20Larsson%20Lush%20Life%20Lyrics.mp3" preload="auto" type="audio/mpeg" />
</audio>
<div id="music-button-container">
<div id="play-pause" class="play"></div>
</div>
<!--<a onclick="musicPlay()"><img src="music2.png" width="65px"></a>-->
</li>
</ul>
这是CSS代码:
#music-button-container,
#play-pause {
cursor: pointer;
height: 50px;
width: 70px;
padding: 12px 18px;
background-repeat: no-repeat;
background-position: center;
background-size: 50px;
}
.play {
background-image: url(./music2.png);
}
.pause {
background-image: url(./equalizer.png) !important;
}
最后,JavaScript代码,我认为问题所在。
var music = document.getElementById('music-button');
var controlButton = document.getElementById('play-pause');
function musicPlay() {
if (music.paused) {
music.play();
controlButton.className = "pause";
} else {
music.pause();
controlButton.className = "play";
}
}
controlButton.addEventListener("click", musicPlay);
music.addEventListener("ended", function () {
controlButton.className = "play";
});
/* This is what I have tried as well*/
document.querySelector(".play-pause").addEventListener("click",
function() {
if (music.paused) {
music.play();
} else {
music.pause();
}
});
function musicPlay() {
var music = document.getElementsById("music-button");
return music.paused ? music.play() : music.pause();
}
var isPlaying = false;
function musicPlay() {
return music.paused ? music.play() : music.pause();
}
music.onplaying = function() {
isPlaying = true;
};
music.onpause = function () {
isPlaying = false;
}
1条答案
按热度按时间6g8kf2rb1#
兄弟如果你只在if语句中使用一个条件,那么它就不会工作想象一下,音频甚至还没有开始,但这并不意味着它被暂停了
这将definetely工作为您的音乐网站提供更多帮助
访问我的https://audioelemente.pages.dev