欢迎访问 生活随笔!

凯发k8官方网

当前位置: 凯发k8官方网 > 前端技术 > html >内容正文

html

点击延迟-凯发k8官方网

发布时间:2024/10/8 html 25 豆豆
凯发k8官方网 收集整理的这篇文章主要介绍了 点击延迟_解决移动端浏览器点击延迟300ms的问题——fastclick用法 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

为什么要使用fastclick

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

项目地址:

ftlabs/fastclick​github.com

fastclick的使用

安装fastclick

安装fastclick可以使用npm,component和bower。另外也提供了ruby版的gem fastclick-rails以及.net提供了nuget package。最直接的可以在页面引入fastclick js文件。如:

  • 在页面直接引入fastclick.js
  • 使用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:

不需要使用fastclick的情况

以下这几种情况是不需要使用fastclick:

1、fastclick是不会对pc浏览器添加监听事件

2、android版chrome 32 浏览器,如果设置viewport meta的值为width=device-width,这种情况下浏览器会马上出发点击事件,不会延迟300毫秒。

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();}};

总结

以上是凯发k8官方网为你收集整理的点击延迟_解决移动端浏览器点击延迟300ms的问题——fastclick用法的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。

  • 上一篇:
  • 下一篇:
网站地图