FastClick

795 阅读2分钟

为什么要用/解决的问题

目的:为了能够立即响应用户的点击事件
原因:移动设备浏览器默认在用户点击屏幕大约延迟300毫秒后才会触发点击事件(为了检查用户是否在做双击)

FastClick安装与使用

安装

在页面直接引入fastclick.js
<script type='application/javascript' src='/path/to/fastclick.js'></script>

使用npm安装
npm install fastclick

初始化FastClick实例

初始化FastClick实例建议在页面的DOM文档加载完成后。

js

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

jQuery

    FastClick.attach(document.body);
});

类似Common JS的模块系统方式

attachFastClick(document.body);

调用require('fastclick')会返回FastClick.attach函数。

注意事项

使用needsclick过滤特定的元素

如果页面上有一些特定的元素不需要使用fastclick来立刻触发点击事件,可以在元素的class上添加needsclick: <a class="needsclick">Ignored by FastClick</a>

不需要使用fastclick的情况

1、FastClick是不会对PC浏览器添加监听事件
2、Android版Chrome 32+浏览器,如果设置viewport meta的值为width=device-width,这种情况下浏览器会马上出发点击事件,不会延迟300毫秒。
<meta name="viewport" content="width=device-width, initial-scale=1">
3、所有版本的Android Chrome浏览器,如果设置viewport meta的值有user-scalable=no,浏览器也会马上出发点击事件。
4、IE11+浏览器设置了css的属性touch-action: manipulation,它会在某些标签(a,button等)禁止双击事件,IE10的为-ms-touch-action: manipulation

常见场景

1.输入框双击才能聚焦
解决方法:在js添加代码

   targetElement.focus();
};

2.上传组件 触发上传需要双击
解决 元素上添加class="needsclick"
3.其他解决方式

FastClick.prototype.needsClick = (target) => {
    switch (target.nodeName.toLowerCase()) {
      // Don't send a synthetic click to disabled inputs (issue #62)
      case 'button':
      case 'select':
      case 'textarea':
        if (!target.disabled) {
          return true;
        }

        break;
      case 'input':
        // File inputs need real clicks on iOS 6 due to a browser bug 
        if ((deviceIsIOS && target.type === 'file') || !target.disabled) {
          return true;
        }

        break;
      case 'label':
      case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
      case 'video':
        return true;

      // **************************************************
      // 添加的click事件的过滤对象
      // 这里写上不阻止冒泡的元素名就可以了
      // **************************************************
      case 'div':
      case 'img':
      case 'p':
      case 'span':
      case 'a':
      case 'i':
        return true;
    }
  };