<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>移动终端</title>
<script>
window.onload=function()
{
var oDiv=document.getElementById('zgz');
var startx = 0;
var starty = 0;
var endx = 0;
var endy = 0;
var movex=0;
var movey=0;
function mobile(json){
document.addEventListener('touchstart',function(event)
{ //触控开始
startx = event.touches[0].pageX;
starty = event.touches[0].pageY;
},false);
document.addEventListener('touchmove',function(event)
{
event.preventDefault();
movex = event.touches[0].pageX;
movey = event.touches[0].pageY;
oDiv.innerHTML=Math.abs(movex-startx)/480
},false);
document.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轴坐标就是向右滑动,否则就是向左滑动
{
//move right
json.right();
}
else
{
//move left
json.left();
}
}
else
{
if( deltay > 0 )//触控结束的Y轴坐标大于触控开始的Y轴坐标就是向下滑动,否则就是向上滑动(这里要注意移动设备上的Y轴的正坐标是向下的。)
{
//move down
json.down();
}
else
{
//move up
json.up();
}
}
},false);
}
mobile({
up:function(){alert('你刚才向上移动了')},
down:function(){ alert('你刚才向下移动了')},
left:function(){ alert('你刚才向左移动了')},
right:function(){alert('你刚才向右移动了')}
});
}
</script>
</head>
<body>
<div id="zgz"></div>