先看效果:
在index.html头部先加上
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport"> <meta content="yes" name="apple-mobile-web-app-capable"> <meta content="black" name="apple-mobile-web-app-status-bar-style"> <meta content="telephone=no" name="format-detection"> <meta content="false" id="twcClient" name="twcClient">
页面样式
#box{position:relative;height:64px;border:1px dashed #000} #bar{position:relative;left:4%;top:16px;width: 90%;height: 10px;border:1px solid #666;border-radius: 5px;background: #fff} #drag-sec{position:absolute;top:-10px; left:2px; width: 16px;height: 30px;border:1px solid #333;background: rgba(0,0,0,.3);border-radius:8px} #min{position: absolute;left: 30px;top: 40px;} #max{position: absolute;right: 30px;top: 40px;} #current{position: absolute;left: 49%;top: 40px;}
引用的js是
<script src="js/zepto.min.js" type="text/javascript"></script>
<script src="js/touch-drag.js" type="text/javascript"></script>
zepto可以自行下载
touch-drag.js代码如下
$(document).ready(function(){ var maxW = $('#bar').width() - $('#drag-sec').width(); var beginX, beginY; var drag_sec = $('#drag-sec'); drag_sec.bind('touchstart', function(e) { console.log(e.type); var evtTouch = e.touches[0]; var x = evtTouch.clientX - beginX; if (x > 0 && x < maxW) drag_sec.css('left', x+'px'); beginX = beginX || evtTouch.clientX; }); drag_sec.bind('touchmove', function(e) { console.log(e.type); var evtTouch = e.touches[0]; if(e.touches[1]) return false; var x = evtTouch.clientX - beginX; if (x > 0 && x < maxW) { drag_sec.css('left', x+'px'); $('#current').text(Math.floor((500+3)/maxW*x)); } e.stopPropagation(); return false; }); drag_sec.bind('touchend', function(e) { console.log(e.type); }); $('#bar').bind('touchstart', function(e) { console.log(e.type); var evtTouch = e.touches[0]; var x = evtTouch.clientX - beginX; console.log(evtTouch.clientX); if (x > 0 && x < maxW) { drag_sec.css('left', x+'px'); $('#current').text(Math.floor((500+3)/maxW*x)); } beginX = beginX || evtTouch.clientX; e.stopPropagation(); return false; }); })