做手机开发时候,简单想用一些动作,如touchLeft,touchRight等,
使用其他库文件就要加载很多不必要的东西,流量的浪费
今天简单写了封装touch的库,简单的监听一些逻辑
onToucheLeft
onTouchRight
onTouchUp
onTouchDown
onTouch
onLongTouch
等等
js部分
1 //简单的touch事件 2 //param:elem touch的对象 3 function SHBTouch(elem){ 4 this.elem = elem ; 5 this.moveLen = 30 ;//当移动距离大于30,触发onTouchLeft,onTouchRight,onTouchUp,onTouchDown 否则触发onTouch 6 this.longTouchTime = 750 ;//当按住元素时间大于750ms,触发onLongTouch 7 this.touchObj = { 8 startX:0,//起始X 9 startY:0,//起始Y 10 curX:0,//结束X 11 curY:0,//结束Y 12 startTime:0//其实时间 13 }; 14 //对元素增加touch事件 15 this.elem.addEventListener('touchstart',funTouchStart) ; 16 this.elem.addEventListener('touchmove',funTouchMove) ; 17 this.elem.addEventListener('touchend',funTouchEnd) ; 18 19 var self = this ; 20 21 function funTouchStart(e){ 22 e.preventDefault(); 23 self.touchObj.startX = e.touches[0].screenX ; 24 self.touchObj.startY = e.touches[0].screenY ; 25 self.touchObj.startTime = (new Date()).getTime(); 26 } 27 28 function funTouchMove(e){ 29 e.preventDefault(); 30 self.touchObj.curX = e.touches[0].screenX ; 31 self.touchObj.curY = e.touches[0].screenY ; 32 } 33 //根据移动距离,和时间判断触发事件 34 function funTouchEnd(e){ 35 e.preventDefault(); 36 var curTime = (new Date()).getTime(); 37 if(Math.abs(self.touchObj.curX - self.touchObj.startX) < self.moveLen){ 38 if(curTime - self.touchObj.startTime > self.longTouchTime){ 39 self.onLongTouch() ; 40 }else{ 41 self.onTouch() ; 42 } 43 }else if(self.touchObj.curX > self.touchObj.startX){ 44 self.onTouchRight() ; 45 }else if(self.touchObj.curX < self.touchObj.startX){ 46 self.onTouchLeft() ; 47 } 48 if(Math.abs(self.touchObj.curY - self.touchObj.startY) < self.moveLen){ 49 if(curTime - self.touchObj.startTime > self.longTouchTime){ 50 self.onLongTouch() ; 51 }else{ 52 self.onTouch() ; 53 } 54 }else if(self.touchObj.curY > self.touchObj.startY){ 55 self.onTouchDown() ; 56 }else if(self.touchObj.curY < self.touchObj.startY){ 57 self.onTouchUp() ; 58 } 59 } 60 } 61 62 SHBTouch.prototype.onTouchLeft = function(){} 63 SHBTouch.prototype.onTouchRight = function(){} 64 SHBTouch.prototype.onTouchUp = function(){} 65 SHBTouch.prototype.onTouchDown = function(){} 66 SHBTouch.prototype.onTouch = function(){} 67 SHBTouch.prototype.onLongTouch = function(){}
html部分
1 <!doctype html> 2 <html> 3 <head> 4 <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" /> 5 </head> 6 <body> 7 <div id="myDemo" style="position:absolute;left:0px;top:0px;height:300px;font-size:100px;line-height:300px;-webkit-transition:300ms;">1323123473131</div> 8 <script src="lib_shb_touch.js"></script> 9 <script> 10 var a = document.getElementById('myDemo') ; 11 var demo = new SHBTouch(a) ; 12 var left = 0 ; 13 demo.onTouchLeft = function(){ 14 left -= 100 ; 15 a.style.left = left+"px" 16 } 17 demo.onTouchRight = function(){ 18 left += 100 ; 19 a.style.left = left+"px" 20 } 21 </script> 22 </html>