一.touchstart
(1).基础概念
click事件得300ms延迟问题,因为苹果得双击缩放判断所以会发生,所以用touch事件来解决这些问题
(2).事件对象
document.addEventListener('touchstart',(e)=>{
console.log(e.target);
},false)
e.changedTouches 与当前事件相关得触点信息(事件触发后所有手指的信息)
e.targetTouches 作用在当前元素上得触点 (只记录手指在该元素上得信息)
(3).封装点击事件
<script>
(function(doc){
let Touch = (selector) =>{
return Touch.prototype.init(selector);
}
Touch.prototype = {
init(selector){
if(typeof(selector) === 'string'){
this.elem = doc.querySelector(selector);
return this;
}
},
tap(callback){
this.elem.addEventListener('touchstart',fn,false)
this.elem.addEventListener('touchend',fn,false)
let sTime,
eTime;
function fn(e){
e.preventDefault();
switch(e.type){
case 'touchstart' :
sTime = new Date().getTime();
break;
case 'touchend' :
eTime = new Date().getTime();
if(eTime - sTime < 500){
callback.call(this,e)
}
break;
}
}
},
longtap(callback){
this.elem.addEventListener('touchstart',fn,false)
this.elem.addEventListener('touchmove',fn,false)
this.elem.addEventListener('touchend',fn,false)
let t = null,
_self = this;
function fn(e){
switch(e.type){
case 'touchstart' :
t = setTimeout(()=>{
callback.call(_self,e)
},500)
break;
case 'touchmove' :
clearTimeout(t);
t= null;
break;
case 'touchend' :
clearTimeout(t);
t= null;
break;
}
}
}
}
window.$ = window.Touch = Touch;
}(document))
$('#box').tap((e)=>{
console.log(1);
})
$('#box').longtap((e)=>{
console.log(2);
})
</script>
在点击后,会触发buuton || a || input得click事件
1.如果用自己封装得则不会,因为通过preventDefault阻止了
oMask.addEventListener('touchstart',()=>{
let _self = this;
setTimeout(()=>{
_self.style.display = 'none'
})
})
<div class="mask"></div>
<div class="opacity-mask"></div>
不再使用touchstart而是用click,既可以解决穿透 也可以解决延迟
二.touchmove
document.addEventListener('touchmove',(e)=>{
console.log(e.target);
},false)
三.touchend
document.addEventListener('touchend',(e)=>{
console.log(e.target);
},false)
四.touchcancel
document.addEventListener('touchcncel',(e)=>{
console.log(e.target);
},false)