我不知道 jQuery mobile,这将是一种更简单的方法,但这里是你可以用普通的 ol' JS 做到这一点的方法:
document.body.addEventListener('touchstart',function(e)
{
e = e || window.event;//don't know how mobile browsers behave here
var startCoordinates = {x:e.changedTouches[0].clientX,
y:e.changedTouches[0].clientY};
var endHandler = function(e)
{
e = e || window.e;
var xDiff = Math.abs(Math.abs(startCoordinates.x) -
Math.abs(e.changedTouches[0].clientX));
//unbind handler, avoid double listeners
document.body.removeEventListener('touchend', endHandler, false);
if (xDiff >= 50)
{//assume small movement wasn't intended as swipe
//here a swipe was detected
if (confirm('Are you sure you want to delete X?'))
{//perform xhr request here, or whatever
}
}
};
document.body.addEventListener('touchend',endHandler,false);
},false);
jQmobile 可能会容易得多,但这是我认为的基本理念,适用于我编写的所有移动浏览器(Android、iOS(4 到 6),甚至是支持触摸的开发模式下的 chrome事件适用于这样的代码)。
更新:
添加了专门处理滑动的代码:
(function(G,und)
{
'use strict';
var load = function()
{
var tStart, body = document.body;
tStart = function(e)
{
e = e || G.event;
var coords = e.changedTouches[0].clientX,
tEnd = function(e)
{
e = e || G.event;
var currentX = e.changedTouches[0].clientX;
if (body.removeEventListener)
{
body.removeEventListener('touchend',tEnd,false);
}
else
{//shouldn't be possible, but I don't know all browsers, of course
body.detachEvent('ontouchend',tEnd);
}
if ((coords - currentX) <= 50)
{//too little movement
/*console.log*/alert('moved, but no real swipe');
}
else
{
/*console.log*/alert('SWIIIPEEE!');
}
};
if (body.addEventListener)
{
return body.addEventListener('touchend',tEnd,false);
}
body.attachEvent('ontouchend',tEnd);
};
if (G.removeEventListener)
{
body.addEventListener('touchstart',tStart,false);
return G.removeEventListener('load',load,false);
}
body.attachEvent('ontouchstart',tStart);
return G.detachEvent('onload',load);
};
if (G.addEventListener)
{
return G.addEventListener('load',load,false);
}
return G.attachEvent('onload',load);
}(this));