mk *_*ing 2 javascript touch touch-event dom-events
我需要 JavaScript 代码来检测未为手机浏览器定义的触摸事件。
例如,从左向右或反向拖动手指。有什么想法或技巧可以做到这一点吗?如果可能的话,如果您不使用 jQuery,我会非常高兴。
使用触摸事件本身非常简单。但是,识别手势需要自定义代码。
将触摸事件添加到窗口的简单示例:
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. ...
Run Code Online (Sandbox Code Playgroud)
识别一个非常简单的水平滑动可能看起来像这样:
// (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!")
}
Run Code Online (Sandbox Code Playgroud)
请记住,这个非常简单的示例没有考虑用户的手指在起点和终点之间所做的事情。因此,在这种情况下,无论用户画一条直线,还是画一个半圆,这些功能都会被触发。任何更复杂或更准确的手势识别都应该在整个拖动(触摸移动)过程中跟踪手指。
| 归档时间: |
|
| 查看次数: |
1425 次 |
| 最近记录: |