處理移動端click事件300ms延遲的好方法—FastClick

下載地址:https://github.com/ftlabs/fastclickjavascript

一、click事件爲何有延遲?java

「...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.」jquery

大概意思就是:從點擊屏幕上的元素到觸發元素的 click 事件,移動瀏覽器會有大約 300 毫秒的等待時間。這是由於瀏覽器想看看你是否是要進行雙擊(double tap)操做。git

二、兼容性github

  • 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

三、何時不用它瀏覽器

fastclick不附加任何監聽器在桌面瀏覽器上面,因此若是你的項目不是針對的移動瀏覽器,那麼就不要使用這個插件。app

Android 設備上的 google瀏覽器 (Chrome) 32+ 版本,在meta頭信息中設置width=device-width 沒有300毫秒的延時,因此也無需使用本插件。jquery插件

<meta name="viewport" content="width=device-width, initial-scale=1">

Chrome瀏覽器在安卓設備上的時候,設置meta頭信息中 user-scalable=no 可是這樣就沒法讓用戶多點觸控縮放網頁了。函數

對於IE11 + 你能夠設置 touch-action: manipulation; 來禁用經過雙擊放大某些元素例如:連接和按鈕的,對於IE10使用 -ms-touch-action: manipulation 。ui

四、使用方法

引入插件的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);
相關文章
相關標籤/搜索