前端面经 click在ios上有300ms延迟,原因及如何解决
原因
2007年苹果发布首款Iphone上ios搭载的safari,为了能把PC端大屏幕的页面以较好的效果展示在小屏幕手机端上,采用了双击缩放(double tap to zoom)的方案。而这就是click在移动端ios会有300ms的缘由。
手机端浏览器不能区分用户的单机操作还是双击操作,所以设置了300ms的延迟时间,用来判断用户是点击还是双击
浏览器会在捕获用户第一次单击时,开启300ms定时,若300ms捕获不到第二次单继,则判断用户就是单击操作;若在300ms内,用户有第二次单继操作,则对区域进行缩放操作
解决方法
禁止缩放
禁止缩放,那么就没有了双击产生缩放的操作,那么就不需要等待300ms
<meta name="viewport" content="width=device-width,user-scalable=no">
css属性解决
touch-action:none;
CSS 属性 touch-action 用于设置触摸屏用户如何操纵元素的区域 (例如,浏览器内置的缩放、平滑功能)
touch-action:none 那么当触控事件发生在元素上时,不进行任何操作——即不会出现滑动和缩放的效果
具体可参考MDN
使用FastClick
原理:在检测到touchend事件的时候,会通过DOM自定义事件立即发出模拟一个click事件,并把300ms之后发出的click事件阻止掉。
使用方法
npm install fastclick
在页面的DOM文档加载完成后,初始化FastClick实例
import fastClick from "fastclick"
fastClick.attach(document.body)
但是使用FastClick,就会发现一个缺点:
在某些ios上,点击输入框启动键盘,触点不是很灵敏,必须重压或者长按才能成功唤启,快速点击是不会唤起软键盘的
解决方法:
FastClick.prototype.focus = function(targetElement) {
var length;
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month' && targetElement.type !== 'email') {
length = targetElement.value.length;
targetElement.focus();
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
建议:在引用fastClick 模块后,重写focus 方法
|