手机滚动条拖动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <title>滚动条拖动评分的JS效果</title> <style> *{ margin: 0;padding: 0; } .scale_panel{ font-size:12px; color:#999; width:100%; line-height:18px; position: relative; width: 90%; margin: 30px auto; height: 60px; } .scale #btn{ background:url(bar.png) no-repeat; width:78px; height:78px; position:absolute; top:-34px; left:0; background-size: 100% 100%; z-index: 100; } .scale{ background:#0a7b57; width:83%; height:10px; position:relative; font-size:0px; top: 7px; margin: 0 auto; } .scale div{ background:#f5a321; width:0px; position:absolute; width:0; left:0; height:10px; bottom:0; } #bar::before{ width: 26px;height: 26px; border-radius: 50%;background: #f5a321; position: absolute; content: ""; left: -22px;top: -8px; z-index: 20; } #bar::after{ width: 26px;height: 26px; border-radius: 50%;background: #0a7b57; position: absolute; content: ""; right: -22px;top: -8px; z-index: 20; } #title{position: absolute;bottom: 11px;left:30px;font-size: 16px;color: #fff;} </style> </head> <body> <div class="scale_panel"> <!-- <img src="left.png" class="left"> --> <div class="scale" id="bar"> <div id="left"></div> <span id="btn"> <span id="title">0%</span> </span> </div> <!-- <img src="right.png" class="right"> --> </div> </body> <script type="text/javascript" src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script> <script> var dx,dy,newLeft,newtop,progress; var barWidth=$("#bar").width(); var barTop=$("#btn").position().top; var leftWidh=60; $("#left").css('width', leftWidh+"px"); $("#btn").css('left', leftWidh+"px"); progress=Math.round(leftWidh/(barWidth-$("#btn").width())*100)+"%"; $("#title").html(progress); document.getElementById('btn').addEventListener('touchstart',function(e){ dx=e.targetTouches[0].pageX-this.offsetLeft; //记录触发拖拽的水平状态发生改变时的位置 dy=e.targetTouches[0].pageY-this.offsetTop; //记录触发拖拽的垂直状态发生改变时的位置 }); document.getElementById('btn').addEventListener('touchmove',function(e){ newLeft=e.targetTouches[0].pageX-dx; //记录拖拽的水平状态发生改变时的位置 console.log(e.targetTouches[0].pageY) newtop=e.targetTouches[0].pageY-dy; if(newtop!=barTop){ newtop=barTop; } if(newLeft<0){ newLeft=0; } if(newLeft>barWidth-$("#btn").width()){ newLeft=barWidth-$("#btn").width(); } this.style.left=newLeft+'px'; this.style.top=newtop+'px'; //设置目标元素的left,top $("#left").css('width', newLeft); progress=Math.round(newLeft/(barWidth-$("#btn").width())*100)+"%"; $("#title").html(progress); }); document.getElementById('btn').addEventListener('touchend',function(e){ }); </script> </html>
一分耕耘,一分收获