1.觸摸事件
觸摸事件使用函數:
//獲取鼠標位置
obj.addEventListener('touchstart',function(e){
startY=e.touches[0].clientY;
})
//得到移動距離,并開始移動
obj.addEventListener('touchmove',function(e){
// console.log(2);
moveY=e.touches[0].clientY;
distanceY=moveY-startY;
addTransition(boxchild);
if((currentY+distanceY)<maxDistance+100&&(currentY+distanceY)>minDistance-100)
setTranslateY(boxchild,currentY+distanceY);
})
//保留當前位置的信息
parentbox.addEventListener('touchend',function(e){7
// console.log(3);
if(currentY+distanceY>maxDistance){
currentY=maxDistance;
}else if(currentY+distanceY<minDistance){
currentY=minDistance;
}else{
currentY=currentY+distanceY;
}
setTranslateY(boxchild,currentY);
})
2.兼容事件
/*定義公用的方法*/
var addTransition = function(obj){
obj.style.webkitTransition = "all .2s";
obj.style.transition = "all .2s";
}
var removeTransition = function(obj){
obj.style.webkitTransition = "none";
obj.style.transition = "none";
}
var setTranslateY = function(obj,y){
obj.style.webkitTransform = "translateY("+y+"px)";
obj.style.transform = "translateY("+y+"px)";
}
2.點擊事件
注意:移動端點擊事件可以使用click事件和自定義事件。
2.1 click事件和自定義事件的區別
click事件的延遲時間大于300ms,自定義事件小于150ms
示例代碼:
click事件
dom.onclick=function(){
//添加事件發生時候的代碼
}
自定義事件(tap)
var hp={};
/*封裝tap*/
hp.tap = function(dom,callback){
/*
* 要求 沒有觸發 touchmove 事件
* 并且響應速度要比click快
*/
if(dom && typeof dom == 'object'){
var isMove = false;
var startTime = 0;
dom.addEventListener('touchstart',function(e){
//console.log('touchstart');
console.time('tap');/*記錄tap這個參數現在的時間*/
startTime = Date.now();
});
dom.addEventListener('touchmove',function(e){
//console.log('touchmove');
isMove = true;
});
dom.addEventListener('touchend',function(e){
//console.log('touchend');
/* //console.timeEnd('tap')/*//*!*打印tap這個參數距離上一次記錄的時候的時間*!/!*!/!*!/*/
/*判讀 是否滿足tap 的要求 一般要求tap的響應時間150*/
if(!isMove && (Date.now()-startTime) < 150){
/*調用 callback*/
callback && callback(e);
}
/*重置 參數*/
isMove = false;
startTime = 0;
});
}
}