fastclick.js --- 解決移動端點擊事件300ms延時

Fast Click 是一個簡單、易用的庫,專爲消除移動端瀏覽器從物理觸摸到觸發點擊事件之間的300ms延時。


爲什麼會存在延遲呢?

從你觸摸按鈕到觸發點擊事件,移動端瀏覽器會等待接近300ms,原因是瀏覽器會等待以確定你是否執行雙擊事件


兼容性

  • 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


何時不需要使用

1、FastClick 不會伴隨監聽任何桌面瀏覽器

2、Android 系統中,在頭部 meta 中設置 width=device-width 的Chrome32+ 瀏覽器不存在300ms 延時,所以,也不需要

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


3、同樣的情況也適用於 Android設備(任何版本),在viewport 中設置 user-scalable=no,但這樣就禁止縮放網頁了


4、IE11+ 瀏覽器中,你可以使用 touch-action: manipulation;  禁止通過雙擊來放大一些元素(比如:鏈接和按鈕)。IE10可以使用 -ms-touch-action: manipulation



使用方法

在 HTML 頁面中引入 fastclick.js

<script type='application/javascript' src='/path/to/fastclick.js'></script>


script 文件必須在頁面元素 實例化 FastClick 之前加載


在 body 上實例化 FastClick ,推薦按照如下方法使用:

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);


示例:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="format-detection" content="telephone=no"/>
    <meta name="format-detection" content="email=no"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <!--[if lt IE 9]>
      <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        a{
            text-decoration: none;
            color:black;
        }
    </style>
</head>
<body>
<a href="#">鏈接</a>

<script src="resources/js/jquery-1.8.3.min.js"></script>
<script src="resources/js/fastclick.js"></script>
<script>
    $(function() {
        FastClick.attach(document.body);
    });
    $('a').click(function(e){
        e.preventDefault();
        $(this).css('color','red');
    });


</script>
</body>
</html>


通過手機來運行這段代碼,使用FastCick事件,可以很明顯看到,點擊鏈接文字變紅時沒有了閃爍效果


Github地址:https://github.com/ftlabs/fastclick



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章