下載地址:https://github.com/ftlabs/fastclick
1、click事件為什么有延遲?
“...mobile browsers will wait approximately 300ms from the time that you tap the button to fire the click event. The reason for this is that the browser is waiting to see if you are actually performing a double tap.”
大概意思就是:從點擊屏幕上的元素到觸發元素的 click
事件,移動瀏覽器會有大約 300 毫秒的等待時間。這是因為瀏覽器想看看你是不是要進行雙擊(double tap)操作。
2、兼容性
- Mobile Safari on iOS 3 and upwards
- Chrome on iOS 5 and upwards
- Chrome on Android (ICS)
- Opera Mobile 11.5 and upwards
- Android Browser since Android 2
- PlayBook OS 1 and upwards
3、什么時候不用它
fastclick不附加任何監聽器在桌面瀏覽器上面,所以如果你的項目不是針對的移動瀏覽器,那么就不要使用這個插件。
Android 設備上的 google瀏覽器 (Chrome) 32+ 版本,在meta頭信息中設置
width=device-width
沒有300毫秒的延時,所以也無需使用本插件。
<meta name="viewport" content="width=device-width, initial-scale=1">
Chrome瀏覽器在安卓設備上的時候,設置meta頭信息中 user-scalable=no
但是這樣就無法讓用戶多點觸控縮放網頁了。
對於IE11 + 你可以設置 touch-action: manipulation;
來禁用通過雙擊放大某些元素例如:鏈接和按鈕的,對於IE10使用 -ms-touch-action: manipulation
。
4、使用方法
引入插件的javascript文件到你的HTML網頁中,像這樣:
<script type='application/javascript' src='/path/to/fastclick.js'></script>
注意:type屬性在HTML5網頁中可以省略不寫。
腳本必須加載到實例化fastclick在頁面的任何元素之前。
實例化 fastclick 最好在body元素的前面,這是使用推薦的方法:
if ('addEventListener' in document) { document.addEventListener('DOMContentLoaded', function() { FastClick.attach(document.body); }, false); }
或者你使用了jquery插件,你可以這樣編寫:
$(function() { FastClick.attach(document.body); });
如果你使用的browserify CommonJS的模塊系統或另一種風格,其 fastclick.attach
函數將返回 require('fastclick')
。作為一個結果,使用fastclick這些裝載機的最簡單的方法如下:
var attachFastClick = require('fastclick'); attachFastClick(document.body);