H5滑动处理
H5简单实现滑动效果
H5滑动处理
//调用
swipe(document.body,{
swipeUp:function(){
$native.alert("Up");
},
swipeDown:function(){
$native.alert("Down");
},
touchMove:function(e){
var target = e.target;
if(target.className !== "book-cover"){//当遇到class=‘book-cover’的时候,不阻止默认行为。
e.preventDefault();
}
},
swipeLeft:function(){
$native.alert("Left");
},
swipeRight:function(){
$native.alert("right");
},
});
function swipe(ele,opts){
var DISTANCE = 40;
var pointStart,
pointEnd;
function init(){
opts = opts ||{};
bindEvent();
}
init();
function bindEvent(){
ele.addEventListener('touchstart',touchStart,false);
ele.addEventListener('touchend',touchEnd,false);
ele.addEventListener('touchmove',touchMove,false);
}
function touchStart(e){
var point = e.touches[0];
pointStart = {
x:point.clientX,
y:point.clientY
}
}
function touchEnd(e){
if(!pointEnd){
return;
}
var y = pointStart.y - pointEnd.y,
absY = Math.abs(y);
x = pointStart.x - pointEnd.x;
absX = Math.abs(x);
if(y<0&&absY>DISTANCE){
swipeUp();
}
if(y>DISTANCE){
swipeDown();
}
if(x<0&&absY>DISTANCE){
swipeLeft();
}
if(x>DISTANCE){
swipeRight();
}
pointStart = undefined;
pointEnd = undefined;
}
function touchMove(e){
var point = e.touches[0];
pointEnd = {
x: point.clientX,
y: point.clientY
}
opts.touchMove&&opts.touchMove(e);
}
function swipeLeft(){
opts.swipeLeft&&opts.swipeLeft();
}
function swipeRight(){
opts.swipeRight&&opts.swipeRight();
}
function swipeUp(){
opts.swipeUp&&opts.swipeUp();
}
function swipeDown(){
opts.swipeDown&&opts.swipeDown();
}
}

浙公网安备 33010602011771号