<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery插件</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<script>
(function($){
$.fn.moveTach=function(json)
{
var i=0;
for(i=0;i<this.length;i++)//重要
{
mobile(this[i],json);
}
function mobile(obj,json){
obj.addEventListener('touchstart',function(event)
{ //触控开始
startx = event.touches[0].pageX;
starty = event.touches[0].pageY;
},false);
obj.addEventListener('touchmove',function(event)
{
event.preventDefault();
movex = event.touches[0].pageX;
movey = event.touches[0].pageY;
obj.innerHTML='x:'+Math.abs(movex)+',y:'+Math.abs(movey);
if(json.swipe)
{
json.swipe();
}
},false);
obj.addEventListener('touchend',function(event)
{ //触控结束
endx = event.changedTouches[0].pageX;
endy = event.changedTouches[0].pageY;
var deltax = endx - startx;
var deltay = endy - starty;
if( Math.abs( deltax ) < 30 && Math.abs( deltay ) < 30 )//当滑动的距离小于30px的时候不做滑动
return;
if( Math.abs( deltax ) >= Math.abs( deltay ) )// 当滑动的X轴距离大于,Y轴的滑动距离->则是水平滑动,否则就是垂直滑动
{
if( deltax > 0 )//触控结束的X轴坐标大于触控开始的X轴坐标就是向右滑动,否则就是向左滑动
{
if(json.right) json.right();
}
else{
if(json.left) json.left();
}
}else{
if( deltay > 0 )//触控结束的Y轴坐标大于触控开始的Y轴坐标就是向下滑动,否则就是向上滑动(这里要注意移动设备上的Y轴的正坐标是向下的。)
{
if(json.down) json.down();
}else{
if(json.up) json.up();
}
}
},false);
};
}})(jQuery)
$(function(){
var oDiv=$('.zgz');
oDiv.moveTach({
up:function(){alert('你刚才向上移动了')},
down:function(){ alert('你刚才向下移动了')},
left:function(){ alert('你刚才向左移动了')},
right:function(){alert('你刚才向右移动了')},
//swipe:function(){alert('滑动了')}
})
})
</script>
<style>
.zgz{ 100%; height:100px; background:#f00; margin: 10px }
</style>
</head>
<body>
<div class="zgz"></div>
<div class="zgz"></div>
<div class="zgz"></div>
<div class="zgz"></div>
</body>
</html>