前些日子在做移動端的開發(fā)策添,早就聽聞移動端有300ms點擊延遲這一個問題恋捆,于是上找?guī)旖鉀Q棵逊。出于好奇心拜讀了一下FastClick庫的源碼,終于搞明白他解決問題的原理悼吱。
本文只做代碼解析慎框,如果對為什么有延遲等有疑問可以看一下我的另一篇文章 http://www.reibang.com/p/9cca518fa87b
1.FastClick解決的問題
移除移動端點擊(click)事件300ms的延遲
2.FastClick結(jié)構(gòu)
源碼是一個單js文件,一共800+的行數(shù)后添,支持amd笨枯,cmd和script直接引入。
;(function () {
// FastClick 構(gòu)造函數(shù) 用來初始化并進(jìn)行事件綁定
function FastClick(layer, options){……}
// 一些判斷瀏覽器環(huán)境的代碼
……
// 為FastClick類添加各種原型方法
// 判斷是否需要原生點擊
FastClick.prototype.needsClick = function(target) {……}
// 判斷是否需要聚焦
FastClick.prototype.needsFocus = function(target){……}
// 向具體元素發(fā)送點擊事件
FastClick.prototype.sendClick = function(targetElement, event){……}
// 決定事件類型
FastClick.prototype.determineEventType = function(targetElement){……}
// 檢查目標(biāo)是否是滾動元素的子元素
FastClick.prototype.updateScrollParent = function(targetElement){……}
// 獲取點擊作用的目標(biāo)
FastClick.prototype.updateScrollParent = function(targetElement){……}
// 為觸摸事件綁定回調(diào)函數(shù)
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對應(yīng)的表單
FastClick.prototype.findControl = function(labelElement){……}
// 為未能取消的事件加保險
FastClick.prototype.onMouse = function(event){……}
// 點擊事件回調(diào)函數(shù)
FastClick.prototype.onClick = function(event){……}
// 移除所有回調(diào)函數(shù)
FastClick.prototype.destroy = function(){……}
// 判斷是否需要FastClick
FastClick.notNeeded = function(layer){……}
// 靜態(tài)工廠方法 暴露接口供使用者調(diào)用
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;
}
})()
可以看出遇西,F(xiàn)astClick的源代碼的結(jié)構(gòu)是非常清晰的馅精。定義了一個FastClick的構(gòu)造函數(shù),為其原型添加共用的方法粱檀,之后添加了靜態(tài)方法洲敢。我們接下來一步一步來剖析源碼。
3.源碼解析
從官網(wǎng)的說明來看茄蚯,我們需要這樣在項目中引入FastClick
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body);
}, false);
}
那么我們的入口就是FastClick.attach這個函數(shù)
FastClick.attach = function(layer, options) {
return new FastClick(layer, options);
};
可以看出這個靜態(tài)方法就是一個工廠函數(shù)压彭,用來創(chuàng)建并返回一個FastClick實例,自然我們看一下FastClick這個構(gòu)造函數(shù)渗常。
function FastClick(layer, options) {
var oldOnClick;
// 一些參數(shù)的定義
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); };
}
// 為函數(shù)綁定上下文
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);
}
// 綁定回調(diào)事件
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.定義了一些我們之后操作需要用到的變量,同時進(jìn)行瀏覽器判斷是否需要FastClick來支持取消300ms的延遲(因為有些設(shè)置天然沒有皱碘,可以移步我開頭的文章询一,在這里我不詳細(xì)說明了)
2.為事件的回調(diào)函數(shù)綁定了FastClick實例
3.為點擊和觸摸事件綁定回調(diào)函數(shù)(最重要的一步)
4.為stopImmediatePropagation做polyfill
也就是說,通過創(chuàng)建實例來為傳入的layer綁定回調(diào)事件來解決問題。下面一一來解析每個事件的回調(diào)函數(shù)
- 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;
// 如果兩次點擊時間差小于預(yù)設(shè)的時間差 則取消第二次點擊
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
event.preventDefault();
}
return true;
};
在onTouchStart中我們主要記錄了這次點擊的一些信息健蕊,包括時間缓醋、位置、點擊作用的元素绊诲。并處理了快速的雙擊要取消第二次點擊的問題。
tips: 在touch事件中調(diào)用event.preventDefault() 是可以取消觸發(fā)原生的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主要是用來區(qū)分是否是一個點擊還是滑動,如果是滑動就取消追蹤這個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的時間差太長應(yīng)為選擇事件
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的延遲。
再來看這兩個關(guān)鍵函數(shù)
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();
}
};
聚焦元素會調(diào)用原生的focus事件槽卫,但是這里面還是有一個小bug的跟压,每次點擊觸發(fā)的時候這個focus的時候,在ios設(shè)備上會選擇到已輸入字符的最后歼培,也就不是自己點擊的那個位置震蒋。
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);
};
使用原生的方法模擬一個鼠標(biāo)事件,并且通過dispatchEvent方法觸發(fā)這個事件躲庄。
- 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這個方法查剖,會阻止其相同層次綁定的其他事件的發(fā)生。
4.總結(jié)
源碼中還有其他的一些函數(shù)噪窘,有興趣可以自行翻閱一下笋庄,整體比較重要部分的分析已經(jīng)寫明了,其中對于各種兼容處理的代碼并沒有說明倔监,感覺也并不是特別的重要直砂,畢竟現(xiàn)在也沒人去支持android2 3了吧,有興趣也可以去讀一讀(畢竟沒有設(shè)備也看不了效果昂葡啊)
源碼還是挺好讀懂的静暂,也學(xué)到了關(guān)于移動端事件的一些知識,對于模擬事件并觸發(fā)的機制也搞懂了瘦锹,感覺收獲還是挺大的籍嘹,(雖然這個庫現(xiàn)在用處也不是很大了,具體原因在文章頭部的那篇文章里有寫)
————————————————————————————
下一個目標(biāo):Axios(請求庫)