我正在尝试建立一个音频播放器,可以在其中将音频片段集进行分组(在我的示例中,Category 1
和Category 2
)。
页面上的任何剪辑都可以播放或暂停,单击另一首曲目将停止当前曲目并播放新曲目。
我还希望播放按钮成为播放器中播放或暂停音频的唯一部分。
我正在尝试修改一些现有代码,但是显然查询选择器不起作用。只是抓一个。
我在这里尝试一些不可能的事情,还是有办法使它工作?
var jukebox = document.querySelector('.audioContent .playButton');
jukebox.addEventListener('click', function(e) {
var songName = e.target.parentElement.getAttribute('data-src');
var audioPlayer = document.querySelector('#player');
if (audioPlayer) {
if (songName === audioPlayer.getAttribute('src')) {
if (audioPlayer.paused) {
audioPlayer.play();
e.target.parentElement.id = 'playing';
} else {
audioPlayer.pause();
e.target.parentElement.id = 'paused';
}
} else {
audioPlayer.src = songName;
audioPlayer.play();
if (document.querySelector('#playing')) {
document.querySelector('#playing').id = '';
} else {
document.querySelector('#paused').id = '';
}
e.target.parentElement.id = 'playing';
}
} else {
var audioPlayer = document.createElement('audio');
audioPlayer.id = 'player';
e.target.parentElement.id = 'playing';
audioPlayer.src = songName;
document.body.appendChild(audioPlayer);
audioPlayer.play();
audioPlayer.addEventListener('ended', function() {
audioPlayer.parentNode.removeChild(audioPlayer);
e.target.parentElement.id = '';
}, false);
}
}, false);
body {
font: normal 15px/15px Helvetica;
background: #259286;
}
/*
************* My Additions *************
*/
.demoCategory li {
list-style: none;
}
.playerWrapper {
background-color: white;
width: 280px;
height: 70px;
margin-top: 5px;
}
.playerInfo {
width: 220px;
height: 70px;
float: right;
background-color: brown;
}
.playerInfo p {
font-size: 1.5em;
padding: 6px 0 0 10px;
font-family: Arial;
color: white;
}
.playButton {
float: left;
width: 38px;
height: 40px;
margin-top: 14px;
background: url(images/media_play_btn.png);
background-repeat: no-repeat;
background-size: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Events</title>
<link rel="stylesheet" href="style2.css" />
</head>
<body>
<div class="audioContent">
<div class="demoCategory">
<h2>Category 1</h2>
<ul>
<li data-src="media/audioClip1.mp3" class="playerWrapper">
<div class="playButton"></div>
<div class="playerInfo">
<p>Audio Clip One</p>
</div>
</li>
<li data-src="media/audioClip2.mp3" class="playerWrapper">
<div class="playButton"></div>
<div class="playerInfo">
<p>Audio Clip Two</p>
</div>
</li>
</ul>
</div>
<div class="demoCategory">
<h2>Category 2</h2>
<ul>
<li data-src="media/audioClip3.mp3" class="playerWrapper">
<div class="playButton"></div>
<div class="playerInfo">
<p>Audio Clip Three</p>
</div>
</li>
<li data-src="media/audioClip4.mp3" class="playerWrapper">
<div class="playButton"></div>
<div class="playerInfo">
<p>Audio Clip Four</p>
</div>
</li>
</ul>
</div>
</div>
<script src="script2.js"></script>
</body>
</html>