2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 点击延迟_解决移动端浏览器点击延迟300ms的问题——FastClick用法

点击延迟_解决移动端浏览器点击延迟300ms的问题——FastClick用法

时间:2023-04-18 10:33:59

相关推荐

点击延迟_解决移动端浏览器点击延迟300ms的问题——FastClick用法

为什么要使用FastClick

移动设备上的浏览器默认会在用户点击屏幕大约延迟300毫秒后才会触发点击事件,这是为了检查用户是否在做双击。为了能够立即响应用户的点击事件,才有了FastClick。

项目地址:

ftlabs/fastclick​

FastClick的使用

安装fastclick

安装fastclick可以使用npm,Component和Bower。另外也提供了Ruby版的gem fastclick-rails以及.NET提供了NuGet package。最直接的可以在页面引入fastclick js文件。如:

在页面直接引入fastclick.js

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

使用npm安装

npm install fastclick

初始化FastClick实例

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

纯Javascript版

// 常规用法if ('addEventListener' in document) {document.addEventListener('DOMContentLoaded', function() {FastClick.attach(document.body); }, false); } // 针对ios 13 bug 可尝试采用if ('addEventListener' in document && 'ontouchstart' in window) {FastClick.prototype.focus = function (targetElement) {targetElement.focus()}document.addEventListener('DOMContentLoaded', function () {FastClick.attach(document.body)}, false)}

jQuery版

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

类似Common JS的模块系统方式

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

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

使用needsclick过滤特定的元素

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

<a class="needsclick">Ignored by FastClick</a>

不需要使用fastclick的情况

以下这几种情况是不需要使用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

存在的问题

有一个问题,就是input的焦点很难获取,往往需要多次点击或者双击才能获取到焦点(大家可以去试试,真的很难点),最开始以为是获取焦点区域太小导致,后来发现是这个fastclick.js框架的问题。

解决方法:

SO,我们点开源码,找到这一段

/*** @param {EventTarget|Element} targetElement*/FastClick.prototype.focus = function(targetElement) {var length;// Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month' && targetElement.type !== 'email') {length = targetElement.value.length;targetElement.focus(); // 加入这一句话就OK了targetElement.setSelectionRange(length, length);} else {targetElement.focus();}};

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。