手机屏幕的触点

虽然jquery mobile有很多事件支持,比如swipe,

但是要给一个小按钮加上swipe的话几乎就没法好好触发事件。

比如吸住底部的工具条,滑动它然后拉出更多内容,就可以采用比较滑动起始点与结束点的大小来判断方向以及方位。

对于手机屏幕,事件还是加在window上最为灵敏,或者也有加在body上的。

window.addEventListener('touchstart', function (e) {
        nStartY = e.targetTouches[0].screenY;
        nStartX = e.targetTouches[0].screenX;
    });
    window.addEventListener('touchend', function (e) {
        nChangY = e.changedTouches[0].screenY;
        nChangX = e.changedTouches[0].screenX;
    }); 

这里的e.targetTouches和e.changedTouches都是JS原生的对象。

打印它们会显示是object list

所以取它们的第一个元素,该元素有几个属性:

client / clientY:// 触摸点相对于浏览器窗口viewport的位置 
pageX / pageY:// 触摸点相对于页面的位置 
screenX /screenY:// 触摸点相对于屏幕的位置 
identifier: // touch对象的unique ID

pageX和pageY会不断增加

screenX和screenY永远相对与屏幕尺寸不变。

 可以适当加上

event.preventDefault(); //阻止触摸时浏览器的缩放、滚动条滚动等  

如果要用jquery 的bind 来监听事件,写法会略有不同,e会被转化成this,具体写法还待有空倒腾一下。

Apple有对这些事件进行说明:

https://developer.apple.com/library/safari/documentation/appleapplications/reference/safariwebcontent/handlingevents/handlingevents.html

用屏幕的触点可以自己模拟swipe事件,在没有这种事件的时候,判断滑动方向:

var start;
$('.slidePics').on("touchstart",getStart, this);
$('.slidePics').on("touchmove",getDirection, this);

function getStart(e){
    start = parseInt(e.targetTouches[0].pageX);
}
function getDirection(e){
    var move = parseInt(e.targetTouches[0].pageX);
    //console.log(start, move)
    if (start < move){
        alert("right")
    }
    else if(start > move){
        alert("left")
    }
}

这里要注意,touchmove的坐标值不停在变化,所以如果用全局变量去保存赋值,是保存不了的。

只有即时拿去与start的坐标进行比较。

原文地址:https://www.cnblogs.com/haimingpro/p/3706293.html