var myTouch = { /* * 给元素绑定tap事件 tap:轻拍、轻触 * @param {object} el 绑定事件的元素 * @param {function} callback 回调函数 */ tap:function(el,callback){ // 1、end-start 时间差 < 150 2、不能滑动 不能触发touchmove if(typeof el === "object"){ var startTime = 0, isMove = false; el.addEventListener("touchstart",function(){ startTime = new Date(); }); el.addEventListener("touchmove",function(){ isMove = true; }); el.addEventListener("touchend",function(e){ var endTime = new Date(); if(endTime-startTime<150&&!isMove){ callback&&callback(e) } isMove = false; startTime = 0; }); } }, /* * 给元素绑定滑动事件 * @param {object} el 绑定事件的元素 * @param {string} dir 滑动的方向 left|right|top|bottom * @param {function} callback 回调函数 */ swiper:function(el,dir,callback){ if(typeof el === "object"){ var p1 = null,p2 = null; el.addEventListener("touchstart",function(e){ p1= { x:e.touches[0].clientX, y:e.touches[0].clientY } // 每 个 Touch 对象代表一个触点,可通过e.touches[0]获取; // 每个触点都由其位置,大小,形状,压力大小,和目标 element 描述。 // TouchList 对象代表多个触点的一个列表. }) el.addEventListener("touchmove",function(e){ p2= { x:e.touches[0].clientX, y:e.touches[0].clientY } }) el.addEventListener("touchend",function(e){ if(p1&&p2&&dir===getDir()){ } }) function getDir(){ // 判断手指滑动的方向 var dir = ""; var diffx = p2.x - p1.x; // 两点的水平差值 var diffy = p2.y - p1.y; // 两点的垂直差值 var absx = Math.abs(diffx); //Math.abs()返回一个数的绝对值 var absy = Math.abs(diffy); if(absx>30 || absy>30){ if(absx>absy){ // 水平滑动 dir = diffx>0 ? "right" : "left"; }else{ // 垂直滑动 dir = diffy>0 ? "bottom" : "top"; } } return dir; } } }}
移动端开发中的一些坑:
_点击事件的第一个问题: _click 事件在移动端会有300ms的延迟响应 。不能及时响应,体验不好。