jquery 音乐播放器
时间: 2023-11-30 17:04:09 浏览: 78
以下是一个基于jQuery库实现的音乐播放器的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>jQuery音乐播放器</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var audio = $("#audio")[0];
var playlist = ["music1.mp3", "music2.mp3", "music3.mp3"];
var index = 0;
var mode = 0; // 0:单曲循环 1:随机播放 2:循环播放
// 播放/暂停
$("#play-pause").click(function(){
if(audio.paused){
audio.play();
$(this).html("暂停"); } else {
audio.pause();
$(this).html("播放");
}
});
// 上一曲
$("#prev").click(function(){
if(mode == 1){
index = Math.floor(Math.random() * playlist.length);
} else {
index = (index - 1 + playlist.length) % playlist.length;
}
audio.src = playlist[index];
audio.play();
});
// 下一曲
$("#next").click(function(){
if(mode == 1){
index = Math.floor(Math.random() * playlist.length);
} else {
index = (index + 1) % playlist.length;
}
audio.src = playlist[index];
audio.play();
});
// 播放模式
$("#mode").click(function(){
mode = (mode + 1) % 3;
if(mode == 0){
$(this).html("单曲循环");
} else if(mode == 1){
$(this).html("随机播放");
} else {
$(this).html("循环播放");
}
});
// 音乐列表
$("#playlist").click(function(){
var list = "";
for(var i = 0; i < playlist.length; i++){
if(i == index){
list += "<li class='active'>" + playlist[i] + "</li>";
} else {
list += "<li>" + playlist[i] + "</li>";
}
}
$("#list").html(list);
$("#list li").click(function(){
index = $(this).index();
audio.src = playlist[index]; audio.play();
$("#play-pause").html("暂停");
$("#list li").removeClass("active");
$(this).addClass("active");
});
});
});
</script>
<style>
#playlist {
cursor: pointer;
}
#list li.active {
color: red;
}
</style>
</head>
<body>
<audio id="audio" src="music1.mp3"></audio>
<button id="prev">上一曲</button>
<button id="play-pause">暂停</button>
<button id="next">下一曲</button>
<button id="mode">单曲循环</button>
<div id="playlist">播放列表</div>
<ul id="list"></ul>
</body>
</html>
```
阅读全文