【发布时间】:2014-07-28 17:51:00
【问题描述】:
我需要 Javascripts 代码来检测未为手机浏览器定义的触摸事件。
例如从左到右或反方向拖动手指。 有什么想法或技巧可以做到这一点吗? 如果可能的话,如果您不要使用 jQuery,我将非常高兴。
【问题讨论】:
标签: javascript touch dom-events touch-event
我需要 Javascripts 代码来检测未为手机浏览器定义的触摸事件。
例如从左到右或反方向拖动手指。 有什么想法或技巧可以做到这一点吗? 如果可能的话,如果您不要使用 jQuery,我将非常高兴。
【问题讨论】:
标签: javascript touch dom-events touch-event
使用触摸事件本身非常简单。但是,识别手势需要自定义代码。
向窗口添加触摸事件的简单示例:
window.addEventListener("touchstart", touchStart, false)
window.addEventListener("touchmove", touchMove, false)
window.addEventListener("touchend", touchEnd, false)
window.addEventListener("touchcancel", touchCancel, false)
window.addEventListener("touchleave", touchLeave, false)
// these functions will run when the events are triggered:
function touchStart(e)
{
var x = e.touches[0].pageX
var y = e.touches[0].pageY
// do more stuff...
}
function touchEnd(e)
{
// ...
}
// etc. ...
识别一个非常简单的水平滑动可能看起来像这样:
// (don't forget the event listeners)
var xStart, yStart
function touchStart(e)
{
xStart = e.touches[0].pageX
yStart = e.touches[0].pageY
}
function touchEnd(e)
{
var xEnd = e.touches[0].pageX, yEnd = e.touches[0].pageY // store the pageX and pageY in variables for readability
if(Math.abs(yStart - yEnd) < 100) // if there was not a lot of vertical movement
{
if(xEnd - xStart > 200) // at least 200 pixels horizontal swipe (to the right)
{
swipeLeftToRight() // swipe recognized
}
else if(xEnd - xStart < -200) // at least -200 pixels of horizontal swipe (to the left)
{
swipeRightToLeft() // swipe recognized
}
}
}
function swipeLeftToRight()
{
alert("You swiped from the left to the right!")
}
function swipeRightToLeft()
{
alert("You swiped from the right to the left!")
}
请记住,这个非常简单的示例没有考虑用户手指在起点和终点之间所做的事情。因此,在这种情况下,无论用户画一条直线,还是画一个半圆,都会触发这些功能。任何更复杂或更准确的手势识别都应在整个拖动过程中跟踪手指(触摸移动)。
【讨论】: