1. tap事件与click事件
移动端click事件缺陷
- 移动端也有click事件,但是在移动端为了区别是点击还是滑动(当用户触碰到屏幕的时候,可能是点击,也可能是活动),因此click事件有300ms的延迟。这个延迟在chrome浏览器模拟器中体现不到300ms的效果,只有在真机上才有。
- 响应太慢,影响用户体验
tap事件
- tap事件不是移动端原生事件,而是通过touch相关事件衍生(封装)过来的。
- tap事件的关键:不触发滑动事件,响应在150ms内
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 200px;
height: 200px;
background-color: hotpink;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
<script>
window.onload = function(){
var bindTapEvent = function(dom, callback){
var startTime = 0;
var isMove = false;
dom.addEventListener('touchstart', function(){
startTime = Date.now();
})
dom.addEventListener('touchmove', function(){
isMove = true;
})
dom.addEventListener('touchend', function(e){
var time = Date.now() - startTime;
if( time < 150 && !isMove ){
callback && callback.call(this, e)
}
// 初始化状态
startTime = 0;
isMove = false;
})
}
bindTapEvent( document.querySelector('.box'), function(e){
console.log('tap事件')
} )
}
</script>
</html>