在ios中使用jQuery的問題:
$(document).ready(function(){
var iX = 0,iY = 0,fX = 0,fY = 0;
document.addEventListener('touchstart', function(e) {
var touch = e.touches[0];
iX = touch.pageX;
iY = touch.pageY;
}, false);
document.addEventListener('touchmove', function(e) {
var touch = e.touches[0];
fX = touch.pageX;
fY = touch.pageY;
}, false);
document.addEventListener('touchcancel', function() {
var dX = fX - iX;
var dY = fY - iY;
var tg = dY/dX;
if(tg < 0) tg = -tg;
if(tg <= 0.5 && fX > iX) rightSwipe()
else if(tg <= 0.5 && fX < iX) leftSwipe()
}, false);
function rightSwipe(){
$("#body").removeClass("bg2");
$("#body").addClass("bg");
}
function leftSwipe(){
$("#body").removeClass("bg");
$("#body").addClass("bg2");
}
});
這個代碼實現的功能是記錄手指觸摸方向,在android4.1.2中chrome浏覽器運行正常,但是在ios中用safari就不運行了。
我沒有在ipad的safari中看見touchcancel
,你改成用touchend
試試:
function upHandler(event) {
var dX = fX - iX;
var dY = fY - iY;
var tg = dY / dX;
if (tg < 0) tg = -tg;
if (tg <= 0.5 && fX > iX) rightSwipe()
else if (tg <= 0.5 && fX < iX) leftSwipe()
}
document.addEventListener('touchcancel', upHandler, false);
document.addEventListener('touchend', upHandler, false);
如果是用jQuery,把下面這行代碼換掉:
document.addEventListener('touchcancel', upHandler, false);
document.addEventListener('touchend', upHandler, false);
換成:
$(document).on('touchcancel, touchend', upHandler);