在移動端,有三種常見的事件類型,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>