最近做项目,有一个滑动音乐播放进度条的效果,但是使用input的 range 来做会出现一些问题,想了想还是用JS来写。直接上代码:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> .progress{position: relative; width:300px;margin:100px auto;} .progress_bg{height: 10px; border: 1px solid #ddd; border-radius: 5px; overflow: hidden;background-color:#f2f2f2;} .progress_bar{background: #5FB878; width: 0; height: 10px; border-radius: 5px;} .progress_btn{width: 20px; height: 20px; border-radius: 5px; position: absolute;background:#fff; left: 0px; margin-left: -10px; top:-5px; cursor: pointer;border:1px #ddd solid;box-sizing:border-box;} .progress_btn:hover{border-color:#F7B824;} </style> </head> <body> <div class="progress"> <div class="progress_bg"> <div class="progress_bar"></div> </div> <div class="progress_btn"></div> <div class="text">0%</div> </div> <script type="text/javascript"> var that =this; var width = document.querySelector('.progress').offsetWidth; var audio=document.querySelector('audio'); /*audio.addEventListener("loadedmetadata", function() {*/ // 拖拽事件 var touch = document.querySelector('.progress_btn'); touch.addEventListener("touchstart",handleStart,false); // 触摸开始 touch.addEventListener("touchmove",handleMove,false); // 开始移动 touch.addEventListener("touchend",handleEnd,false); // 触摸结束 var x1,y1,oldTime,newTime,olfLeft,newLeft; function handleStart(e){ e.preventDefault(); var touches = e.changedTouches; x1 = touches[0].pageX; y1 = touches[0].pageY; olfLeft = document.querySelector('.progress_btn').offsetLeft; // document.getElementById("audio").pause(); // that.pause=true; } function handleMove(e){ e.preventDefault(); var x2 = e.changedTouches[0].pageX; var y2 = e.changedTouches[0].pageY; newLeft = x2-x1; nowLeft = olfLeft+newLeft; if(nowLeft<0){ nowLeft = 0; } if(nowLeft>width){ nowLeft = width; } document.querySelector('.progress_bar').style.width=nowLeft+"px"; document.querySelector('.progress_btn').style.left=(nowLeft-(nowLeft>(width-10)?10:5))+"px"; var per = nowLeft/width; console.log(per); // that.nowAudioTime = 136 * per;//音频应该显示的时间 // that.current_time=that.nowAudioTime; // audio.currentTime = that.nowAudioTime; } function handleEnd(e){ touch.removeEventListener("touchmove",handleEnd,false); // document.querySelector('audio').currentTime = that.nowAudioTime; // console.log(document.querySelector('audio').currentTime); // document.querySelector('audio').play(); // that.pause=false; } </script> </body> </html>