移动端涉及到的触摸操作比较复杂,所以在设计上,移动端浏览器会在 touchend
和 click
之间有 300ms 左右的延迟间隔来判断用户是单击还是双击屏幕,所以在移动端浏览器经常看到,我们可以双击屏幕来放大显示的范围,但是在开发中,我们要消除这些延迟,所以总结了一下几个方法
情景再现,运行下面代码,要在移动端预览,可以看出平均延迟在 200ms 左右
<!DOCTYPE html><html> <head> <title></title> <meta charset="utf-8" /> <style type="text/css"> #div1 { width: 50px; height: 50px; line-height: 50px; border: 1px solid #333; } </style> </head> <body> <div id="div1">click</div> <h3 id="timeTxt"></h3> <script type="text/javascript"> var div1 = document.getElementById('div1'); var timeTxt = document.getElementById('timeTxt'); var last; div1.addEventListener('touchend', function () { last = +new Date(); }); div1.addEventListener('click', function () { timeTxt.innerText = +new Date() - last + 'ms'; }); </script> </body></html>
meta 标签
在头部添加以下 meta 标签,禁止网页缩放
<meta name="viewport" content="width=device-width" />
touch-action 属性
利用 css3 的 touch-action 属性,他的作用是防止你的双击行为,缺点就是兼容性不高
html { -ms-touch-action: manipulation; // ie10 touch-action: manipulation;}
利用第三方库
fastclick 这个基本用在移动端浏览器来取消这 300ms 的延迟操作,用起来十分方便,大小只有几 k,地址:fastclick,使用方法如下
if ('addEventListener' in document) { document.addEventListener( 'DOMContentLoaded', function () { FastClick.attach(document.body); }, false );}// jquery用法$(function () { FastClick.attach(document.body);});