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 延时,所以,也不需要
1
|
<
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
1
|
<
script
type
=
'application/javascript'
src
=
'/path/to/fastclick.js'
></
script
>
|
script 文件必须在页面元素 实例化 FastClick 之前加载
在 body 上实例化 FastClick ,推荐按照如下方法使用:
1
2
3
4
5
|
if
(
'addEventListener'
in
document) {
document.addEventListener(
'DOMContentLoaded'
,
function
() {
FastClick.attach(document.body);
},
false
);
}
|
如果你使用的是 jQuery
1
2
3
|
$(
function
() {
FastClick.attach(document.body);
});
|
如果你使用的是 Browserify 或其他 CommonJS 风格的模块系统,FastClick.attach 方法会在你调用 require('fastclick') 之后返回。所以,使用 FastClick 最简单的方法如下:
1
2
|
var
attachFastClick = require(
'fastclick'
);
attachFastClick(document.body);
|
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
<!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
本文转自 frwupeng517 51CTO博客,原文链接:http://blog.51cto.com/dapengtalk/1886507