移动端tap事件封装:
处理移动端的点击、长按和滑动操作(由于我们做的都是适配移动端的页面,因此不用考虑双击),思路:
按下时记录手指的初始坐标和初始时间
touchmove事件函数中记录手指的当前坐标,并执行事件函数,用当前坐标 - 初始坐标 = 移动距离(X轴-X轴,Y轴-Y轴)来判断移动方向
手指抬起时touchend,记录结束时间,如果移动距离小于6像素(非移动事件时)执行点击事件,根据当前时间 - 初始时间 = 点击时长来判断是点击还是长按。
在这里插入代码片
function tap(obj,attr,fn){
obj.addEventListener("touchstart",function (){
var ose = {
"sTime" : Date.now(),
"eTime" : Date.now(),
"sX" : event.touches[0].pageX,
"sY" : event.touches[0].pageY,
"eX" : event.touches[0].pageX,
"eY" : event.touches[0].pageY
}
obj.addEventListener("touchmove",function (){
ose.eX = event.touches[0].pageX;
ose.eY = event.touches[0].pageY;
})
obj.addEventListener("touchend",function (){
ose.eTime = Date.now();
if(Math.abs(ose.eX-ose.sX)<5&&Math.abs(ose.eY-ose.sY)<5){
if((ose.eTime-ose.sTime)<300){
if(attr=="点击"){
fn.call(obj);
}
}else{
if(attr=="长按"){
fn.call(obj);
}
}
}else{
if(Math.abs(ose.eX-ose.sX)>Math.abs(ose.eY-ose.sY)){
if(ose.eX>ose.sX){
if(attr=="右滑"){
fn.call(obj);
}
}else{
if(attr=="左滑"){
fn.call(obj);
}
}
}else{
if(ose.eY>ose.sY){
if(attr=="下滑"){
fn.call(obj);
}
}else{
if(attr=="上滑"){
fn.call(obj);
}
}
}
}
})
})
}
## 函数调用
```javascript
在这里插入代码片
tap(document,"右滑",function (){
document.body.style.backgroundColor = "red";
})
tap(document,"左滑",function (){
document.body.style.backgroundColor = "blue";
})
tap(document,"上滑",function (){
document.body.style.backgroundColor = "green";
})
tap(document,"下滑",function (){
document.body.style.backgroundColor = "yellow";
})
tap(document,"点击",function (){
document.body.style.backgroundColor = "black";
})
tap(document,"长按",function (){
document.body.style.backgroundColor = "white";
})