How to make my 'click' function work with iOS

前端 未结 5 1710
面向向阳花
面向向阳花 2020-11-28 11:53

I have a set of Div\'s which act as buttons. These buttons have a simple jquery click() function which works in all browsers except iOS.

For example:



        
相关标签:
5条回答
  • 2020-11-28 12:34

    Also based on Marek's answer, which adapts the event to the device to fire a function, here is a code that force to fire a click on iOS devices, where there is first a touchstart event :

    var UA = navigator.userAgent,
    iOS = !!(UA.match(/iPad|iPhone/i));
    
    if (iOS) {
       $(document).on('touchstart', function (e) {
           e.target.click();
       });
    }
    
    0 讨论(0)
  • 2020-11-28 12:38

    You can use this:

    $('button').bind( "touchstart", function(){
        alert('hi');
    });
    

    Another Solution is to set the element's cursor to pointer and it work with jQuery live and click event. Set it in CSS.

    0 讨论(0)
  • 2020-11-28 12:42

    Click ": means When a mousedown and mouseup event occur on the same element OR an element is activated by the keyboard.

    from Jquery Bug, there is work around , Just add "cursor: pointer" to the element's CSS and the click event will work as expected. and you can even see this Jquery click on Ios for help

    0 讨论(0)
  • 2020-11-28 12:43

    Based on Marek's answer this is my take on it (it's a bit cleaned up):

    var ua = navigator.userAgent, 
    pickclick = (ua.match(/iPad/i) || ua.match(/iPhone/)) ? "touchstart" : "click";
    
    $('.clickable_element').on(pickclick, function(e) {
         // do something here
    });
    

    There's still a lot of work ahead for the industry when it comes to standards…

    EDIT:

    Didn't work out on Android phones. Took a more rigid approach:

    if (document.documentElement.clientWidth > 1025) { pickclick = 'click' }
    if (document.documentElement.clientWidth < 1025) { pickclick = 'touchstart' }
    
    $('.clickable_element').on(pickclick, function(e) {
         // do something here
    });
    
    0 讨论(0)
  • 2020-11-28 12:44

    Actually, the accepted answer did not work for me. I tried using "cursor:pointer", onclick="", and even convert the element to an anchor tag.

    What i did to make it work is to bind the touchstart event insted of the click event. To make it work on all platforms i had to to an ugly ua spoofing like this:

    var ua = navigator.userAgent,
    event = (ua.match(/iPad/i) || ua.match(/iPhone/)) ? "touchstart" : "click";
    
    jQuery("body").on(event, '.clickable_element', function(e) {
        // do something here
    });
    
    0 讨论(0)
提交回复
热议问题