开发者

How do I cancel a touch action on Mobile Safari?

开发者 https://www.devze.com 2023-01-31 08:09 出处:网络
Say I have an button with a touchEnd event listener. If I touch the button, slide my finger out of the button and then release touch, I\'d like to \"cancel\" the touch event.

Say I have an button with a touchEnd event listener. If I touch the button, slide my finger out of the button and then release touch, I'd like to "cancel" the touch event.

This behaves correctly if I do the following using onClick:

buttonElement.ad开发者_如何学CdEventListener('click', function (event) {
    if (event.target === this) {
    // Do something
    }
});

However, this doesn't work with "touchEnd" because event.target points to the originating element (buttonElement in this case), not to the element where I released touch.

Is there a better generic way to do this besides doing something like setting a flag on "touchMove"? Thanks!


Use the touch events: touchstart, touchmove, touchcancel, touchend. See the Apple docs.

Regardless, I don't think I'd try to cancel the event. On the event I would check the location of the "cursor" (finger) and if it was outside of the area, just not fire the function.


I know the question is old, but I'm searching how to do the same thing, and I wrote a code that works, and if anyone need this later.

I just canceling the default action if the touch move. Works pretty well on my WebApp, and the feedback is much better than dealing with mouseup and mousedown events, on mobile safari is too slow.

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!");
}

*add this functions to theirs respective event listeners


Long time ago but I just wanted to add my 2c worth since there's no accepted answer for this question yet.

touchCancel isn't very reliable on the mobile platforms at the moment.

See: http://alxgbsn.co.uk/2011/12/23/different-ways-to-trigger-touchcancel-in-mobile-browsers/

Alternatively you could go the route of writing your own sort-of event overlay like what's done in Hammer.JS

That way you can determine the type of gesture before you cancel.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号