前些日子在做移动端的开发,早就听闻移动端有300ms点击延迟这一个问题,于是上找库解决。出于好奇心拜读了一下FastClick库的源码,终于搞明白他解决问题的原理。
本文只做代码解析,如果对为什么有延迟等有疑问可以看一下我的另一篇文章 http://www.jianshu.com/p/9cca518fa87b
1.FastClick解决的问题
移除移动端点击(click)事件300ms的延迟
2.FastClick结构
源码是一个单js文件,一共800+的行数,支持amd,cmd和script直接引入。
;(function () {
// FastClick 构造函数 用来初始化并进行事件绑定
function FastClick(layer, options){……}
// 一些判断浏览器环境的代码
……
// 为FastClick类添加各种原型方法
// 判断是否需要原生点击
FastClick.prototype.needsClick = function(target) {……}
// 判断是否需要聚焦
FastClick.prototype.needsFocus = function(target){……}
// 向具体元素发送点击事件
FastClick.prototype.sendClick = function(targetElement, event){……}
// 决定事件类型
FastClick.prototype.determineEventType = function(targetElement){……}
// 检查目标是否是滚动元素的子元素
FastClick.prototype.updateScrollParent = function(targetElement){……}
// 获取点击作用的目标
FastClick.prototype.updateScrollParent = function(targetElement){……}
// 为触摸事件绑定回调函数
FastClick.prototype.onTouchStart = function(event){……}
FastClick.prototype.touchHasMoved = function(event){……}
FastClick.prototype.onTouchMove = function(event){……}
FastClick.prototype.onTouchEnd = function(event){……}
FastClick.prototype.onTouchCancel = function(){……}
// 获取label对应的表单
FastClick.prototype.findControl = function(labelElement){……}
// 为未能取消的事件加保险
FastClick.prototype.onMouse = function(event){……}
// 点击事件回调函数
FastClick.prototype.onClick = function(event){……}
// 移除所有回调函数
FastClick.prototype.destroy = function(){……}
// 判断是否需要FastClick
FastClick.notNeeded = function(layer){……}
// 静态工厂方法 暴露接口供使用者调用
FastClick.attach = function(layer, options){……}
// 模块加载适配
if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
// AMD. Register as an anonymous module.
define(function() {
return FastClick;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = FastClick.attach;
module.exports.FastClick = FastClick;
} else {
window.FastClick = FastClick;
}
})()
可以看出,FastClick的源代码的结构是非常清晰的。定义了一个FastClick的构造函数,为其原型添加共用的方法,之后添加了静态方法。我们接下来一步一步来剖析源码。
3.源码解析
从官网的说明来看,我们需要这样在项目中引入FastClick
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body);
}, false);
}
那么我们的入口就是FastClick.attach这个函数
FastClick.attach = function(layer, options) {
return new FastClick(layer, options);
};
可以看出这个静态方法就是一个工厂函数,用来创建并返回一个FastClick实例,自然我们看一下FastClick这个构造函数。
function FastClick(layer, options) {
var oldOnClick;
// 一些参数的定义
options = options || {};
/**
* Whether a click is currently being tracked.
*
* @type boolean
*/
this.trackingClick = false;
/**
* Timestamp for when click tracking started.
*
* @type number
*/
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
*
* @type EventTarget
*/
this.targetElement = null;
/**
* X-coordinate of touch start event.
*
* @type number
*/
this.touchStartX = 0;
/**
* Y-coordinate of touch start event.
*
* @type number
*/
this.touchStartY = 0;
/**
* ID of the last touch, retrieved from Touch.identifier.
*
* @type number
*/
this.lastTouchIdentifier = 0;
/**
* Touchmove boundary, beyond which a click will be cancelled.
*
* @type number
*/
this.touchBoundary = options.touchBoundary || 10;
/**
* The FastClick layer.
*
* @type Element
*/
this.layer = layer;
/**
* The minimum time between tap(touchstart and touchend) events
*
* @type number
*/
this.tapDelay = options.tapDelay || 200;
/**
* The maximum time for a tap
*
* @type number
*/
this.tapTimeout = options.tapTimeout || 700;
if (FastClick.notNeeded(layer)) {
return;
}
// Some old versions of Android don't have Function.prototype.bind
function bind(method, context) {
return function() { return method.apply(context, arguments); };
}
// 为函数绑定上下文
var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
var context = this;
for (var i = 0, l = methods.length; i < l; i++) {
context[methods[i]] = bind(context[methods[i]], context);
}
// Set up event handlers as required
if (deviceIsAndroid) {
layer.addEventListener('mouseover', this.onMouse, true);
layer.addEventListener('mousedown', this.onMouse, true);
layer.addEventListener('mouseup', this.onMouse, true);
}
// 绑定回调事件
layer.addEventListener('click', this.onClick, true);
layer.addEventListener('touchstart', this.onTouchStart, false);
layer.addEventListener('touchmove', this.onTouchMove, false);
layer.addEventListener('touchend', this.onTouchEnd, false);
layer.addEventListener('touchcancel', this.onTouchCancel, false);
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
// layer when they are cancelled.
// 对stopImmediatePropagation做polyfill
if (!Event.prototype.stopImmediatePropagation) {
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener;
if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture);
} else {
rmv.call(layer, type, callback, capture);
}
};
layer.addEventListener = function(type, callback, capture) {
var adv = Node.prototype.addEventListener;
if (type === 'click') {
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
if (!event.propagationStopped) {
callback(event);
}
}), capture);
} else {
adv.call(layer, type, callback, capture);
}
};
}
// If a handler is already declared in the element's onclick attribute, it will be fired before
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
// adding it as listener.
if (typeof layer.onclick === 'function') {
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick;
layer.addEventListener('click', function(event) {
oldOnClick(event);
}, false);
layer.onclick = null;
}
}
看懂代码并不难,主要过程就是
1.定义了一些我们之后操作需要用到的变量,同时进行浏览器判断是否需要FastClick来支持取消300ms的延迟(因为有些设置天然没有,可以移步我开头的文章,在这里我不详细说明了)
2.为事件的回调函数绑定了FastClick实例
3.为点击和触摸事件绑定回调函数(最重要的一步)
4.为stopImmediatePropagation做polyfill
也就是说,通过创建实例来为传入的layer绑定回调事件来解决问题。下面一一来解析每个事件的回调函数
- touchstart
FastClick.prototype.onTouchStart = function(event) {
var targetElement, touch, selection;
if (event.targetTouches.length > 1) {
return true;
}
targetElement = this.getTargetElementFromEventTarget(event.target);
touch = event.targetTouches[0];
// 对ios做一些兼容性处理
if (deviceIsIOS) {
selection = window.getSelection();
// 处理是否为长按选中
if (selection.rangeCount && !selection.isCollapsed) {
return true;
}
if (!deviceIsIOS4) {
if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
event.preventDefault();
return false;
}
this.lastTouchIdentifier = touch.identifier;
this.updateScrollParent(targetElement);
}
}
// 追踪这个点击事件并记录一些信息
this.trackingClick = true;
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement;
this.touchStartX = touch.pageX;
this.touchStartY = touch.pageY;
// 如果两次点击时间差小于预设的时间差 则取消第二次点击
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
event.preventDefault();
}
return true;
};
在onTouchStart中我们主要记录了这次点击的一些信息,包括时间、位置、点击作用的元素。并处理了快速的双击要取消第二次点击的问题。
tips: 在touch事件中调用event.preventDefault() 是可以取消触发原生的click事件的 同理作用于focus事件 mouseup等。这也正是FastClick的原理之一。
- touchmove
FastClick.prototype.onTouchMove = function(event) {
if (!this.trackingClick) {
return true;
}
// If the touch has moved, cancel the click tracking
if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
this.trackingClick = false;
this.targetElement = null;
}
return true;
};
onTouchMove主要是用来区分是否是一个点击还是滑动,如果是滑动就取消追踪这个click
- touchend
FastClick.prototype.onTouchEnd = function(event) {
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
// 如果不存在追踪click直接返回
if (!this.trackingClick) {
return true;
}
// 取消第二次延迟
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
this.cancelNextClick = true;
return true;
}
// touchend于touchstart的时间差太长应为选择事件
if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
return true;
}
this.cancelNextClick = false;
this.lastClickTime = event.timeStamp;
trackingClickStart = this.trackingClickStart;
this.trackingClick = false;
this.trackingClickStart = 0;
if (deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0];
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
}
targetTagName = targetElement.tagName.toLowerCase();
// ******重点******
// 如果点击的是一个label 则需要聚焦到label for的元素
if (targetTagName === 'label') {
forElement = this.findControl(targetElement);
if (forElement) {
this.focus(targetElement);
if (deviceIsAndroid) {
return false;
}
targetElement = forElement;
}
} else if (this.needsFocus(targetElement)) {
// 如果是一个需要focus的元素,则聚焦他并模拟一个点击事件
if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
this.targetElement = null;
return false;
}
this.focus(targetElement);
this.sendClick(targetElement, event);
if (!deviceIsIOS || targetTagName !== 'select') {
this.targetElement = null;
event.preventDefault();
}
return false;
}
if (deviceIsIOS && !deviceIsIOS4) {
scrollParent = targetElement.fastClickScrollParent;
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
return true;
}
}
// 如果元素需要点击事件 则阻止原生点击 并模拟一个点击事件
if (!this.needsClick(targetElement)) {
event.preventDefault();
this.sendClick(targetElement, event);
}
return false;
};
这里正是FastClick的精髓,取消原生点击事件并立马模拟一个点击事件来取消这300ms的延迟。
再来看这两个关键函数
FastClick.prototype.focus = function(targetElement) {
var length;
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month' && targetElement.type !== 'email') {
length = targetElement.value.length;
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
聚焦元素会调用原生的focus事件,但是这里面还是有一个小bug的,每次点击触发的时候这个focus的时候,在ios设备上会选择到已输入字符的最后,也就不是自己点击的那个位置。
FastClick.prototype.sendClick = function(targetElement, event) {
var clickEvent, touch;
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
if (document.activeElement && document.activeElement !== targetElement) {
document.activeElement.blur();
}
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
};
使用原生的方法模拟一个鼠标事件,并且通过dispatchEvent方法触发这个事件。
- touchcancel
FastClick.prototype.onTouchCancel = function() {
this.trackingClick = false;
this.targetElement = null;
};
onTouchCancel只是取消了追踪
- click
FastClick.prototype.onClick = function(event) {
var permitted;
if (this.trackingClick) {
this.targetElement = null;
this.trackingClick = false;
return true;
}
if (event.target.type === 'submit' && event.detail === 0) {
return true;
}
permitted = this.onMouse(event);
if (!permitted) {
this.targetElement = null;
}
return permitted;
};
主要是针对于捕捉的点击事件使用prevent并没有取消掉原生点击事件的问题
- mouse
FastClick.prototype.onMouse = function(event) {
if (!this.targetElement) {
return true;
}
if (event.forwardedTouchEvent) {
return true;
}
if (!event.cancelable) {
return true;
}
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
event.propagationStopped = true;
}
// Cancel the event
event.stopPropagation();
event.preventDefault();
return false;
}
return true;
};
主要是理解一下stopImmediatePropagation这个方法,会阻止其相同层次绑定的其他事件的发生。
4.总结
源码中还有其他的一些函数,有兴趣可以自行翻阅一下,整体比较重要部分的分析已经写明了,其中对于各种兼容处理的代码并没有说明,感觉也并不是特别的重要,毕竟现在也没人去支持android2 3了吧,有兴趣也可以去读一读(毕竟没有设备也看不了效果啊)
源码还是挺好读懂的,也学到了关于移动端事件的一些知识,对于模拟事件并触发的机制也搞懂了,感觉收获还是挺大的,(虽然这个库现在用处也不是很大了,具体原因在文章头部的那篇文章里有写)
————————————————————————————
下一个目标:Axios(请求库)