alloyfinger是一款非常轻量的开源手势库,由于其轻量、基于原生js等特性被广泛使用。关于其原理,它的官方团队解析的非常详细——传送门。相信学过高数的人看起来应该不难,这里不深入解析了。
其核心代码只有300多行,完成了14个手势,其手势并不是浏览器原生的事件,而是通过监听touchstart、touchmove、touchend、touchcancel四个原生浏览器事件hack出来的手势,故其用法与原生可能有些不同。比如阻止默认事件、阻止冒泡,不能像原生事件那样用。
官方代码除了alloyfinger的核心库外还有react、vue的实现。在这里只对核心库即vue版本的解析。
核心库:
/* AlloyFinger v0.1.10
* By dntzhang
* Github: https://github.com/AlloyTeam/AlloyFinger
* Note By keenjaan
* Github: https://github.com/keenjaan
*/
; (function () {
// 计算距离和角度等的数学公式
// 根据两边的长度求直角三角形斜边长度(主要用于求两点距离)
function getLen(v) {
return Math.sqrt(v.x * v.x + v.y * v.y);
}
// 主要用于计算两次手势状态间的夹角的辅助函数
function dot(v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
}
// 计算两次手势状态间的夹角
function getAngle(v1, v2) {
var mr = getLen(v1) * getLen(v2);
if (mr === 0) return 0;
var r = dot(v1, v2) / mr;
if (r > 1) r = 1;
return Math.acos(r);
}
// 计算夹角的旋转方向,(逆时针大于0,顺时针小于0)
function cross(v1, v2) {
return v1.x * v2.y - v2.x * v1.y;
}
// 将角度转换为弧度,并且绝对值
function getRotateAngle(v1, v2) {
var angle = getAngle(v1, v2);
if (cross(v1, v2) > 0) {
angle *= -1;
}
return angle * 180 / Math.PI;
}
// 用于处理手势监听函数的构造函数
var HandlerAdmin = function(el) {
this.handlers = []; // 监听函数列表
this.el = el; // 监听元素
};
// 构造函数的添加监听函数的方法
HandlerAdmin.prototype.add = function(handler) {
this.handlers.push(handler);
}
// 构造函数的删除监听函数的方法
HandlerAdmin.prototype.del = function(handler) {
if(!handler) this.handlers = []; // handler为假值时,代表清空监听函数列表
for(var i=this.handlers.length; i>=0; i--) {
if(this.handlers[i] === handler) {
this.handlers.splice(i, 1);
}
}
}
// 触发用户事件监听回调函数
HandlerAdmin.prototype.dispatch = function() {
for(var i=0,len=this.handlers.length; i 0 && this.delta <= 250 && Math.abs(this.preTapPosition.x - this.x1) < 30 && Math.abs(this.preTapPosition.y - this.y1) < 30);
}
this.preTapPosition.x = this.x1; // 将此次的触摸坐标保存到preTapPosition。
this.preTapPosition.y = this.y1;
this.last = this.now; // 记录本次触摸时间点
var preV = this.preV, // 获取记录的两点坐标差值
len = evt.touches.length; // 手指个数
if (len > 1) { // 手指个数大于1
this._cancelLongTap(); // 取消longTap定时器
this._cancelSingleTap(); // 取消singleTap定时器
var v = { x: evt.touches[1].pageX - this.x1, y: evt.touches[1].pageY - this.y1 };
// 计算两个手指间横纵坐标差,并保存到prev对象中,也保存到this.preV中。
preV.x = v.x;
preV.y = v.y;
this.pinchStartLen = getLen(preV); // 计算两个手指的间距
this.multipointStart.dispatch(evt); // 触发multipointStart事件
}
// 开启longTap事件定时器,如果750ms内定时器没有被清除则触发longTap事件。
this.longTapTimeout = setTimeout(function () {
this.longTap.dispatch(evt);
}.bind(this), 750);
},
move: function (evt) {
if (!evt.touches) return;
var preV = this.preV, // start方法中保存的两点横纵坐标差值。
len = evt.touches.length, // 手指个数
currentX = evt.touches[0].pageX, // 第一个手指的x坐标
currentY = evt.touches[0].pageY; // 第一个手指的y坐标
this.isDoubleTap = false; // 移动了就不能是双击事件了
if (len > 1) {
// 获取当前两点横纵坐标的差值,保存到v对象中。
var v = { x: evt.touches[1].pageX - currentX, y: evt.touches[1].pageY - currentY };
// start保存的preV不为空,pinchStartLen大于0
if (preV.x !== null) {
if (this.pinchStartLen > 0) {
// 当前两点的距离除以start中两点距离,求出缩放比,挂载到evt对象中
evt.zoom = getLen(v) / this.pinchStartLen;
this.pinch.dispatch(evt); // 触发pinch事件
}
evt.angle = getRotateAngle(v, preV); // 计算旋转的角度,挂载到evt对象中
this.rotate.dispatch(evt); // 触发rotate事件
}
preV.x = v.x; // 将move中的两个手指的横纵坐标差值赋值给preV,同时也改变了this.preV
preV.y = v.y;
} else {
// 出列一根手指的pressMove手势
// 第一次触发move时,this.x2为null,move执行完会有给this.x2赋值。
if (this.x2 !== null) {
// 用本次的move坐标减去上一次move坐标,得到x,y方向move距离。
evt.deltaX = currentX - this.x2;
evt.deltaY = currentY - this.y2;
} else {
// 第一次执行move,所以移动距离为0,将evt.deltaX,evt.deltaY赋值为0.
evt.deltaX = 0;
evt.deltaY = 0;
}
// 触发pressMove事件
this.pressMove.dispatch(evt);
}
// 触发touchMove事件,挂载不同的属性给evt对象抛给用户
this.touchMove.dispatch(evt);
// 取消长按定时器,750ms内可以阻止长按事件。
this._cancelLongTap();
this.x2 = currentX; // 记录当前第一个手指坐标
this.y2 = currentY;
if (len > 1) {
evt.preventDefault(); // 两个手指以上阻止默认事件
}
},
end: function (evt) {
if (!evt.changedTouches) return;
// 取消长按定时器,750ms内会阻止长按事件
this._cancelLongTap();
var self = this; // 保存当前this对象。
// 如果当前留下来的手指数小于2,触发multipointEnd事件
if (evt.touches.length < 2) {
this.multipointEnd.dispatch(evt);
}
// this.x2或this.y2存在代表触发了move事件。
// Math.abs(this.x1 - this.x2)代表在x方向移动的距离。
// 故就是在x方向或y方向移动的距离大于30px时则触发swipe事件
if ((this.x2 && Math.abs(this.x1 - this.x2) > 30) ||
(this.y2 && Math.abs(this.y1 - this.y2) > 30)) {
// 计算swipe的方向并写入evt对象。
evt.direction = this._swipeDirection(this.x1, this.x2, this.y1, this.y2);
this.swipeTimeout = setTimeout(function () {
self.swipe.dispatch(evt); // 异步触发swipe事件
}, 0)
} else {
this.tapTimeout = setTimeout(function () {
self.tap.dispatch(evt); // 异步触发tap事件
// trigger double tap immediately
if (self.isDoubleTap) { // start方法中计算的满足双击条件时
self.doubleTap.dispatch(evt); // 触发双击事件
clearTimeout(self.singleTapTimeout); // 清楚singleTap事件定时器
self.isDoubleTap = false; // 重置双击条件
}
}, 0)
if (!self.isDoubleTap) { // 如果不满足双击条件
self.singleTapTimeout = setTimeout(function () {
self.singleTap.dispatch(evt); // 触发singleTap事件
}, 250);
}
}
this.touchEnd.dispatch(evt); // 触发touchEnd事件
// end结束后重置相关的变量
this.preV.x = 0;
this.preV.y = 0;
this.zoom = 1;
this.pinchStartLen = null;
this.x1 = this.x2 = this.y1 = this.y2 = null;
},
cancel: function (evt) {
// 关闭所有定时器
clearTimeout(this.singleTapTimeout);
clearTimeout(this.tapTimeout);
clearTimeout(this.longTapTimeout);
clearTimeout(this.swipeTimeout);
this.touchCancel.dispatch(evt);
},
_cancelLongTap: function () {
clearTimeout(this.longTapTimeout); // 关闭longTap定时器
},
_cancelSingleTap: function () {
clearTimeout(this.singleTapTimeout); // 关闭singleTap定时器
},
_swipeDirection: function (x1, x2, y1, y2) {
// 判断swipe方向
return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
},
// 给14中手势中一种手势添加监听函数
on: function(evt, handler) {
if(this[evt]) { // 事件名在这14中之中,才添加函数到监听事件中
this[evt].add(handler);
}
},
// 给14中手势中一种手势移除监听函数
off: function(evt, handler) {
if(this[evt]) { // 事件名在这14中之中,才移除相应监听函数
this[evt].del(handler);
}
},
// 清空,重置所有数据
destroy: function() {
// 关闭所有定时器
if(this.singleTapTimeout) clearTimeout(this.singleTapTimeout);
if(this.tapTimeout) clearTimeout(this.tapTimeout);
if(this.longTapTimeout) clearTimeout(this.longTapTimeout);
if(this.swipeTimeout) clearTimeout(this.swipeTimeout);
// 移除touch的四个事件
this.element.removeEventListener("touchstart", this.start);
this.element.removeEventListener("touchmove", this.move);
this.element.removeEventListener("touchend", this.end);
this.element.removeEventListener("touchcancel", this.cancel);
// 清除所有手势的监听函数
this.rotate.del();
this.touchStart.del();
this.multipointStart.del();
this.multipointEnd.del();
this.pinch.del();
this.swipe.del();
this.tap.del();
this.doubleTap.del();
this.longTap.del();
this.singleTap.del();
this.pressMove.del();
this.touchMove.del();
this.touchEnd.del();
this.touchCancel.del();
// 重置所有变量
this.preV = this.pinchStartLen = this.zoom = this.isDoubleTap = this.delta = this.last = this.now = this.tapTimeout = this.singleTapTimeout = this.longTapTimeout = this.swipeTimeout = this.x1 = this.x2 = this.y1 = this.y2 = this.preTapPosition = this.rotate = this.touchStart = this.multipointStart = this.multipointEnd = this.pinch = this.swipe = this.tap = this.doubleTap = this.singleTap = this.pressMove = this.touchMove = this.touchEnd = this.touchCancel = null;
return null;
}
};
// 如果当前环境支持module,exports等es6语法,则导出AlloyFingerPlugin模块
if (typeof module !== 'undefined' && typeof exports === 'object') {
module.exports = AlloyFinger;
} else { // 否则将AlloyFingerPlugin注册到全局对象
window.AlloyFinger = AlloyFinger;
}
})();
vue 版本代码:
/* AlloyFinger v0.1.0 for Vue
* By june01
* Github: https://github.com/AlloyTeam/AlloyFinger
* Note By keenjaan
* Github: https://github.com/keenjaan
*/
; (function() {
var AlloyFingerPlugin = {
// 用于vue挂载指令的install函数
install: function(Vue, options) {
// options挂载指令时传递的参数
options = options || {};
// AlloyFinger全局中获取,没有就读取options中获取。
var AlloyFinger = window.AlloyFinger || options.AlloyFinger;
// 判断vue的版本
var isVue2 = !!(Vue.version.substr(0,1) == 2);
// 获取不到AlloyFinger抛出异常
if(!AlloyFinger) {
throw new Error('you need include the AlloyFinger!');
}
// 14中手势命名
var EVENTMAP = {
'touch-start': 'touchStart',
'touch-move': 'touchMove',
'touch-end': 'touchEnd',
'touch-cancel': 'touchCancel',
'multipoint-start': 'multipointStart',
'multipoint-end': 'multipointEnd',
'tap': 'tap',
'double-tap': 'doubleTap',
'long-tap': 'longTap',
'single-tap': 'singleTap',
'rotate': 'rotate',
'pinch': 'pinch',
'press-move': 'pressMove',
'swipe': 'swipe'
};
// 记录元素添加监听事件的数组。
var CACHE = [];
// 创建空对象,用于存放vue自定义指令directive的参数对象
var directiveOpts = {};
// 获取某个元素在CACHE中是否存在,存在返回index,不存在返回null
var getElemCacheIndex = function(elem) {
for(var i=0,len=CACHE.length; i
上面是整个代码解析,其中有几个问题点:
1、长按是否需要取消tap、swipe、touchend、singleTap、doubleTap等end里面的所有事件。
如果要取消end里的所有事件,就要添加一个字段isLongTap, 在触发longTap事件时设置为true。在end里判断isLongTap的值,如果为true则return掉,阻止end里的所有事件,并将isLongTap重置为false
2、swipe事件和doubleTap的界定,源码中对swipe与tap的区别是move的距离,当move的距离在x、y方向上都小于等于30px时就为tap事件,大于30px时就为swipe事件。doubleTap也一样,两次点击的距离在x、y方向上都小于等于30px,其界定的30px是设置了如下代码:
即设置页面宽度为设备的理想视口。在我的实际项目中如果进行如上设置,30px这个值可能有点大,会导致想触发swipe事件结果变成了tap事件。至于到底多少,你们可以试一下效果,找到符合你们团队的分界值。
还有就是在实际的移动项目中,我们可能并不会这样设置你的视口,比如淘宝团队的flexible适配。其ios端对页面视口进行了缩放,android端都是用的理想视口(没有缩放视口),这样就造成30px对应到屏幕的滑动距离不同。在ios端滑动距离较小就能触发swipe事件。这种情况下就不能直接使用,要结合你的移动端适配库,要对alloyfinger源码做调整。
关于移动端适配可以查看我的这篇文章 传送门
方法一:在alloyfinger源码中直接读取viewport的缩放,对于不同适配机型设置不同的修正值,使得在所有机型上触发swipe事件,手指移动的距离相同。
方法二:是对于vue版本的实现,通过vue的自定义指令,在挂在指令时,动态的通过参数传进去。
Vue.use(AlloyFingerVue, option) // 通过参数传进去。
在AlloyFingerPlugin的install函数中获取option对象,再将option对象注入到alloyfinger对象中,在alloyfinger中再对swipe的分界值进行修正。
具体实现方案我源码中已实现,注释写的很清楚,不懂可以问我,源码链接见文章结尾。
3、阻止冒泡,因为其事件除了touchstart、touchmove、touchend、touchcancel四个原生事件外,其它都是hack的,所以并不能像原生事件那样在监听函数中写阻止冒泡。需要在相应的原生事件中阻止冒泡。在vue版本中可以通过注册指令时,传入参数来阻止冒泡。如:
v-finger:tap.stoppropagation
在doOnOrOff函数中可以通过modifiers字段读取到stoppropagation字段,再将stoppropagation字段注册到alloyfinger对象中。在alloyfinger对象对去该字段来判断是否需要阻止冒泡。
优点: 阻止冒泡非常方便,在绑定事件时加一个修饰符即可。
缺点:一旦阻止了冒泡,该元素上所有的事件都阻止了冒泡,如果某一事件需要冒泡,还需特殊处理。
针对以上三点,在官方版本进行了修改。源码请见 传送门
官方项目vue版本bug
最近在项目中遇到了个问题,有些页面按钮绑定事件失败。最后找到了问题,官方的vue版本适配有bug。
当使用vue-router切换路由时,上一个页面销毁时,所有绑定事件的元素都会触发doUnbindEvent函数,当一个元素绑定多个事件时,doUnbindEvent函数会触发多次。对于一个元素如下:
按钮
doUnbindEvent函数:
var doUnbindEvent = function(elem) {
var index = getElemCacheIndex(elem);
if ( index ) {
return true;
}
if(!isNaN(index)) {
var delArr = CACHE.splice(index, 1);
if(delArr.length && delArr[0] && delArr[0].alloyFinger.destroy) {
delArr[0].alloyFinger.destroy();
}
}
};
第一次触发doUnbindEvent函数, index一定能返回一个number类型数字,会从CACHE中删除该元素。
当第二次触发doUnbindEvent时,由于该元素已被删除所以index会返回null,而if条件并不能拦截null这个值,
if(!isNaN(index)) {
//
}
故:
delArr = CACHE.splice(index, 1) = CACHE.splice(null, 1) = CACHE.splice(0, 1);
变成了始终截取CACHE数组中第一个元素。
而当路由切换时,上一个页面触发doUnbindEvent函数,新页面触发doBindEvent函数,而这两者是同时触发,导致一边向CACHE数组中添加绑定元素,一边从CACHE数组中移除元素。当一个元素绑定多个事件时,存在index为null,会移除新页面元素刚刚绑定的事件。导致新页面绑定事件失败。
已向官方提交了issue。链接