一、click等事件在移动端的延迟
click事件在移动端和pc端均可以触发,但是在移动端有延迟现象。
1、背景
由于早期移动设备浏览网页时内容较小,为了增强用户体验,苹果公司专门为移动设备设计了双击放大的功能,以确保用户可以方便地放大网页内容,但是当用户单击按钮的时候,移动设备需要延迟约300ms执行,以判断用户是否是要双击
2、验证
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><metaname="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/><title>click的延迟</title><style type="text/css">html,body {height: 100%;}body {background-color: hotpink;}</style><script src="https://cdn.bootcss.com/eruda/1.4.3/eruda.min.js"></script><script>eruda.init();</script></head><body></body>
</html><script type="text/javascript">window.onload = function() {document.body.onclick = function() {console.log("click延迟", Date.now() - startTime);};//定义一些必须要使用的变量var startTime = 0;document.body.addEventListener("touchstart", function(e) {console.log(e);console.log("touchstart");//获取当前系统时间startTime = Date.now();});document.body.addEventListener("touchmove", function() {console.log("touchmove");});document.body.addEventListener("touchend", function() {console.log("touchend");//计算 差值console.log("时差", Date.now() - startTime);});};
</script>
移动端 事件响应原则:优先响应移动端独有事件
二、解决办法
1、使用touch事件模拟click事件
如下使用touchstart和touched封装了一个移动端的tap事件
var idcast = {// 传入dom元素tap: function(dom, callback) {//判断是否传入了dom元素,或者dom元素是否是一个对象if (!dom || typeof dom != "object") {return;}var startX, startY, time, moveX, moveY, distanceX, distanceY;dom.addEventListener("touchstart", function(e) {if (e.targetTouches.length > 1) {return;}startX = e.targetTouches[0].clientX;startY = e.targetTouches[0].clientY;time = Date.now();});dom.addEventListener("touchend", function(e) {if (e.changedTouches.length > 1) {//说明不止一个手指return;}//判断时间差异if (Date.now() - time > 150) {console.log("长按操作");return;}//获取松开手指的时候的坐标与触摸开始时的坐标差异moveX = e.changedTouches[0].clientX;moveY = e.changedTouches[0].clientY;distanceX = moveX - startX;distanceY = moveY - startY;//判断坐标差异if (Math.abs(distanceX) < 6 && Math.abs(distanceY) < 6) {//说明是点击而非滑动//执行tap事件相应之后的处理操作//若函数不为空才调用callback && callback(e);console.log("移动端点击单击事件--tap事件");} else {console.log("滑动操作");}});}};
可以直接调用idcast中tap方法。
2、使用zepto中已经封装好的tap事件直接调用
$(menuBox).on("tap",callback)
zepto下载链接: https://github.com/madrobby/zepto