【问题标题】:jQuery .click() not working on iOS Safari even after trying some of the known fixesjQuery .click() 即使在尝试了一些已知的修复后也无法在 iOS Safari 上运行
【发布时间】:2018-03-28 02:36:12
【问题描述】:

我在试图弄清楚这一点时遇到了一些麻烦。我无法让 JQuery .click() 事件在 iOS Safari 上工作,即使在尝试了一些已知的解决方法之后也是如此。

我的代码:

HTML:

<div class="mobile-nav-menu">
       <a href="#" onclick="void(0)">
          <img id="hamburger-menu-icon" src="assets/dot-menu.svg">
       </a>
</div>

JS(省略变量声明以节省篇幅):

     window.onload = () => {
       hamburgerMenuIcon.click(toggleMobileNavDropdown);
     }

     const toggleMobileNavDropdown = () => {

        if(mobileNavDropdown.height() == 0) {

            mobileNavDropdown.css({
                height: '180px',
                width: '200px'
            })
            mobileNavContents.delay(800).fadeIn(900);

        } else if(mobileNavDropdown.height() == 180) {

            mobileNavContents.fadeOut(400);

            setTimeout(() =>  {
                mobileNavDropdown.css({
                height: '0px',
                width: '0px'
            })
            }, 400)
        }
    }

这在除 Safari iOS 之外的任何浏览器(无论是移动设备还是桌面设备)中都绝对没有问题。我在 Google 上花了一些时间,并遇到了一些已知的解决方法。这是我迄今为止尝试过的但没有成功的方法:

  • 我已尝试将cursor: pointer; 应用于链接。据我所知,没有这个 Safari,iOS 不会将该元素注册为可点击。

  • 由于添加 cursor CSS 属性不起作用,我尝试将onclick="void(0)" 添加到 HTML 中,如上面的 HTML sn-p 所示。这是我在 Stack 上遇到的另一个建议,我假设它以某种方式允许 Safari iOS 将元素注册为可点击。

  • 在第三次尝试中,我尝试将点击事件更改为 vanilla JS,并添加 touchstart and tap:

    hamburgerMenuIcon.on("click touchstart tap", toggleMobileNavDropdown);
    

到目前为止,什么都没有。有什么建议?

【问题讨论】:

    标签: javascript jquery html ios css


    【解决方案1】:

    我这样做,首先这部分是为了阻止事件多次发生,因为我接下来要做的事情会冒泡:

    function eventHandler(event, selector) {
        event.stopPropagation(); // Stop event bubbling.
        event.preventDefault(); // Prevent default behaviour
        if (event.type === 'touchend' || event.type === 'touchcancel')
          selector.off('click'); // If event type was touch turn off clicks to prevent phantom clicks.
      }
    

    然后对于实际的元素交互(你不一定需要去抖动部分,但我觉得它很有帮助,如果你喜欢我会给你链接那个插件,重量很轻而且很有帮助):

    $(".selection-button").on('click touchend touchcancel', $.debounce(
      100,
      function(e) {
    
        //whatever you want to do
    
      }));
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 2018-10-03
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多