How to replace click with touchstart on iOS devices

前端 未结 3 385
礼貌的吻别
礼貌的吻别 2020-12-09 20:29

Objective

To close the parent div of an anchor tag when clicked. In the code below, I want to hide div performance_tt when the user

相关标签:
3条回答
  • 2020-12-09 21:04

    See http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html

    For iOS mouse events like click do not bubbe unless:

    • The target element of the event is a link or a form field.
    • The target element, or any of its ancestors up to but not including the , has an explicit event handler set for any of the mouse events. This event handler may be an empty function.
    • The target element, or any of its ancestors up to and including the document has a cursor: pointer CSS declarations.

    The easiest solution for me is to apply cursor: pointer everywhere in case it is a iOS touch device. As there's no cursor it does not have any visual impact

    0 讨论(0)
  • 2020-12-09 21:11

    Define a clickhandler that you can use later on:

    var clickHandler = ('ontouchstart' in document.documentElement ? "touchstart" : "click");
    
    $("a").bind(clickHandler, function(e) {
        alert("clicked or tapped. This button used: " + clickHandler);
    });
    

    This will trigger click on non-touch devices and touchstart on touch devices.

    When that is said, I will strongly recommend using Fast click instead, and use regular click-events. With the above solution, you will trigger "touchstart" on links when you swipe on it to scroll the page for instance - which is not ideal.

    0 讨论(0)
  • 2020-12-09 21:20

    In iOs a tag is a clickable element, so touch on the link will trigger the mouse events (including click).

    This code

    $("#close_performance_tt").bind('click',function() { 
        alert('Click event triggered');                             
    }); 
    

    will work fine on iOs.

    For more information: http://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html

    0 讨论(0)
提交回复
热议问题