播放音乐进度条
css页面
*{ padding: 0; margin: 0; } .btn{ height: 32px; width: 32px; cursor: pointer; } .play{ display: block; width: 40px; height: 40px; margin-top: -5px; } .pause{ display: none; width: 40px; height: 40px; margin-top: -5px; } .audioPlayer{ position: relative; width: 570px; height: 42px; border-radius: 10px; margin: 300px auto; padding-top: 14px; padding-left: 20px; background-color: #1b6d85; } .totalProgress{ cursor: pointer; position: absolute; top: 26px; left: 72px; width: 500px; height: 8px; background-color: white; border-radius: 10px; } .currentProgress{ width: 0; height: 100%; -webkit-border-top-left-radius:10px ; -webkit-border-bottom-left-radius: 10px; background-color: #00a1d6; } .time{ display: block; margin-left: 10px; position: absolute; top: 2px; left: 72px; color: white; }
js
var audio = document.getElementById('audio'); var totalProgress = $('.totalProgress'); var currentProgress = $('.currentProgress'); var currentTime = $('.currentTime'); var totalTime = $('.totalTime'); var timer;//计时器 //按钮单击时 $('.btn').on('click',function(){ //如果音频暂停 if(audio.paused){ audio.play();//播放音频 //更改播放按钮 $(".play").css({'display':'none'}); $(".pause").css({'display':'block'}); //计时器实时更改进度条 timer= setInterval(function(){ if (audio.ended) { //如果音频播放结束 $(".play").css({'display':'block'}); $(".pause").css({'display':'none'}); } else{ //更改时间(duration属性返回音频的长度,以秒计) currentTime.text(audio.currentTime); totalTime.text(audio.duration); //更改进度条 var ratio = audio.currentTime/audio.duration; currentProgress.css({'width':ratio*100+'%'}); } },100); }else{ audio.pause();//暂停音频 //更改播放按钮 $(".play").css({'display':'block'}); $(".pause").css({'display':'none'}); } }); //单击进度条更改进度 totalProgress.on('click',function(ev){ //获取百分比 var ratio = getRatio(ev); currentProgress.css({'width':ratio * 100 + '%' }); //更改音频进度条 audio.currentTime = audio.duration * ratio; }); function getRatio (ev) { //总进度条的实际长度 var totawidth = totalProgress[0].offsetWidth; //总进度条的X坐标 var totalX = totalProgress.offset().left; //鼠标的x坐标 var mouseX = ev.clientX; //求出百分比 var ratio = (mouseX-totalX) / totawidth; return ratio; }
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>音乐播放器</title> <link rel="stylesheet" type="text/css" href="css/a.css"/> </head> <body> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <div class="audioPlayer"> <div class="time"> <span class="currentTime">00:00</span> / <span class="totalTime">00:00</span> </div> <div class="btn"> <img src="img/b.png" class="play"/> <img src="img/a.png" class="pause"/> </div> <!--controls autoplay loop--> <audio id="audio" src="音乐地址"></audio> <div class="totalProgress"> <div class="currentProgress"></div> </div> </div> <script src="js/a.js" type="text/javascript" charset="utf-8"></script> </body> </html>