Fast Click 是一個簡單、易用的庫,專爲消除移動端瀏覽器從物理觸摸到觸發點擊事件之間的300ms延時。javascript
爲何會存在延遲呢?css
從你觸摸按鈕到觸發點擊事件,移動端瀏覽器會等待接近300ms,緣由是瀏覽器會等待以肯定你是否執行雙擊事件
html
兼容性html5
Mobile Safari on iOS 3 and upwardsjava
Chrome on iOS 5 and upwardsjquery
Chrome on Android (ICS)git
Opera Mobile 11.5 and upwardsgithub
Android Browser since Android 2瀏覽器
PlayBook OS 1 and upwardsapp
什麼時候不須要使用
一、FastClick 不會伴隨監放任何桌面瀏覽器
二、Android 系統中,在頭部 meta 中設置 width=device-width 的Chrome32+ 瀏覽器不存在300ms 延時,因此,也不須要
<meta name="viewport" content="width=device-width, initial-scale=1">
三、一樣的狀況也適用於 Android設備(任何版本),在viewport 中設置 user-scalable=no,但這樣就禁止縮放網頁了
四、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