jquery音乐播放器
时间: 2023-11-30 20:04:10 浏览: 78
以下是一个简单的jQuery音乐播放器的实现方法:
HTML部分:
```html
<div class="player">
<audio id="audio" src=""></audio>
<ul class="playlist">
<li data-src="song1.mp3">歌曲1</li>
<li data-src="song2.mp3">歌曲2</li>
<li data-src="song3.mp3">歌曲3</li>
</ul>
<div class="controls">
<button class="play-pause">播放</button>
<button class="stop">停止</button>
<button class="prev">上一曲</button>
<button class="next">下一曲</button>
</div>
</div>
```
CSS部分:
```css
.player {
width: 300px;
margin: 0 auto;
text-align: center;
}
.playlist {
list-style: none;
padding: 0;
margin: 0;
}
.playlist li {
cursor: pointer;
margin: 5px;
}
.playlist li.active {
color: red;
}
.controls {
margin-top: 10px;
}
.play-pause, .stop, .prev, .next {
margin: 5px;
}
```
JavaScript部分:
```javascript
$(function() {
var audio = $('#audio')[0];
var playlist = $('.playlist');
var tracks = playlist.find('li');
var len = tracks.length;
var currentTrack = 0;
var playing = false;
audio.volume = 0.8;
playlist.on('click', 'li', function(e) {
e.preventDefault();
var clicked = $(this);
currentTrack = clicked.index();
run(clicked, audio);
});
$('.play-pause').on('click', function(e) {
e.preventDefault();
if (playing == false) {
audio.play();
playing = true;
$(this).text('暂停');
} else {
audio.pause();
playing = false;
$(this).text('播放');
}
});
$('.stop').on('click', function(e) {
e.preventDefault();
audio.pause();
audio.currentTime = 0;
playing = false;
$('.play-pause').text('播放');
});
$('.prev').on('click', function(e) {
e.preventDefault();
if (currentTrack == 0) {
currentTrack = len - 1;
} else {
currentTrack--;
}
run($(tracks[currentTrack]), audio);
});
$('.next').on('click', function(e) {
e.preventDefault();
if (currentTrack == len - 1) {
currentTrack = 0;
} else {
currentTrack++;
}
run($(tracks[currentTrack]), audio);
});
function run(clicked, player) {
var src = clicked.attr('data-src');
playlist.find('.active').removeClass('active');
clicked.addClass('active');
player.src = src;
audio.load();
audio.play();
playing = true;
$('.play-pause').text('暂停');
}
});
```
阅读全文