fastclick使用与解密

来源:互联网 发布:java手游 编辑:程序博客网 时间:2024/05/31 18:44

  • 什么是 fastclick
  • 为什么要使用 fastclick
    • 1直接去掉延迟
    • 2缓和修复
  • 如何使用 fastclick
  • 什么时候不使用它

什么是 fastclick

FastClick is a simple, easy-to-use library for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile browsers. The aim is to make your application feel less laggy and more responsive while avoiding any interference with your current logic.

fastclick,消除点击延时提高程序的运行效率。

为什么要使用 fastclick

According to Google:

…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.

众所周知,移动端在处理点击事件的时候,会有300毫秒的延迟。恰恰是这300毫秒的延迟,会让人有一种卡顿的体验。

这300毫秒的原因,在于早期浏览器的实现中,浏览器不知道用户触摸后,到底想做什么,所以故意等待300毫秒,再触发click事件。

既然我们已经知道了原因了,怎么解决呢?

1、直接去掉延迟

因为浏览器对 click 事件的处理,有 300ms 的延迟,而 touchstart 几乎是立即执行的,估将所有 click 事件的监听,改为 touchstart 事件的监听,即可消除这 300ms 的延迟。

但这样副作用也很大,移动端的交互体验全靠触摸,touchstart 将会干扰其他交互行为的处理,例如滚动、拖拽等。

2、缓和修复

使用 fastclick.

如何使用 fastclick

既然浏览器有这 300ms 的延迟,那么我们来代替浏览器判断,手动触发 click 事件,这也是 fastClick 的解决方案。

1、引入插件的 JavaScript 文件到你的 HTML 网页中:

<script type="application/javascript" src="/js/fastclick.js"></script>

脚本必须加载到实例化 fastclick 在页面的任何元素之前
实例化 fastclick 最好在 body 元素的前面,这是使用推荐的方法

if('addEventListener' in document) {  document.addEventListener('DOMContentLoaded', function(){    FastClick.attach(document.body);  },false);}

2、jQuery 中使用

$(function(){  FastClick.attach(document.body);});

3、如果你使用了 browserify CommonJS 的模块系统或另一种风格。

var attachFastClick = require("fastclick");attachFastClick(document.body);

什么时候不使用它

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

原创粉丝点击