在移动端,有三种常见的事件类型,click事件、touch事件、tap事件。它们的区别如下:
- click事件:click事件是在用户点击屏幕的时候触发,如果是移动设备,则会在用户点击屏幕的同时触发touch事件。但是,click事件的响应时间比touch事件慢,因为click事件需要等待用户离开屏幕后才能触发。
- touch事件:touch事件是在用户触摸屏幕的时候触发,可以监听到触摸的开始、移动、结束等状态。但是touch事件并不能判断用户的手指是点击了屏幕还是滑动了屏幕。
- tap事件:tap事件是在用户点击屏幕的时候触发,与click事件类似,但是响应时间比click事件快。它是通过监听touchstart和touchend事件来模拟的,可以判断用户的手指是点击了屏幕还是滑动了屏幕。
下面是一个简单的demo,可以用来验证这三种事件的区别:
<!DOCTYPE html> <html> <head> <title>移动端事件</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <style> .box{ width: 200px; height: 200px; background-color: #ccc; margin: auto; margin-top: 100px; text-align: center; line-height: 200px; font-size: 20px; } </style> </head> <body> <div class="box" id="box1">click事件</div> <div class="box" id="box2">touch事件</div> <div class="box" id="box3">tap事件</div> <script> var box1 = document.getElementById('box1'); var box2 = document.getElementById('box2'); var box3 = document.getElementById('box3'); // click事件 box1.addEventListener('click', function(){ alert('click'); }); // touch事件 box2.addEventListener('touchstart', function(){ alert('touchstart'); }); box2.addEventListener('touchmove', function(){ alert('touchmove'); }); box2.addEventListener('touchend', function(){ alert('touchend'); }); // tap事件 var startTime, endTime; box3.addEventListener('touchstart', function(){ startTime = new Date().getTime(); }); box3.addEventListener('touchend', function(){ endTime = new Date().getTime(); if(endTime - startTime < 300){ alert('tap'); } }); </script> </body> </html>