2010-12-17 46 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!"); 
} 

*添加此功能,以他們各自的事件偵聽器