2010-12-17 47 views
1

假设我有一个带有touchEnd事件侦听器的按钮。如果我触摸按钮,将手指滑出按钮然后释放触摸,我想“取消”触摸事件。如何在Mobile Safari上取消触摸操作?

这如果我下面用onClick正确行为:

buttonElement.addEventListener('click', function (event) { 
    if (event.target === this) { 
    // Do something 
    } 
}); 

然而,这不符合“touchEnd”工作,因为event.target指向发起元素(buttonElement在这种情况下),不到我释放触摸的元素。

除了像在touchMove上设置标志之外,还有更好的通用方法吗?谢谢!

回答

1

使用触摸事件:touchstart,touchmove,touchcancel,touchend。请参阅Apple docs

无论如何,我不认为我会尝试取消该活动。关于事件,我会检查“光标”(手指)的位置,如果它位于该区域之外,则不会触发该功能。

+0

这是做到这一点的正确方法。 touchcancel仅在用户收到呼叫或推送通知时发生。 – ughoavgfhw 2010-12-17 21:50:13

+0

是的,我知道touchCancel是如何触发的,因此引号中的“取消”。所以基本上没有办法跟踪事件监听器之外的某个状态吗? – thatmarvin 2010-12-20 17:10:01

0

我知道这个问题很旧,但我正在寻找如何做同样的事情,并且我编写了一个可以工作的代码,并且稍后有人需要。

我只是取消默认动作,如果触摸移动。在我的WebApp上工作得非常好,并且反馈比处理mouseup和mousedown事件要好得多,但在移动Safari中速度太慢。

var moved=false; 

function touchstart(){ 
    moved=false; 
    //highlight button for feedback 
} 

function touchmove(){ 
    moved=true; 
} 

function touchend(){ 
    //undo-highlight the button 

    if(moved) touchcanceled(); 
    else action(); 
} 

function touchcanceled(){ 
    //user just flicked the button, 
    //probably scrolling the view 
} 

function action(){ 
    alert("You triggered me!"); 
} 

*添加此功能,以他们各自的事件侦听器