点击外面的隐藏div在iPad上不起作用

时间:2022-08-26 20:32:39

I have the following code:

我有以下代码:

$(document).on('click touch', function(e) {
    var nav    = $(e.target).closest('.nav-js-trigger');
    var hidden = $(e.target).closest('.show-nav')

    if ( nav.length > 0 ) {
        $('.show-nav').not( nav.next().toggleClass('show-nav') ).removeClass('show-nav');
    } else if ( hidden.length === 0 ) {
        $('.show-nav').removeClass('show-nav');
    }
});

It hides the menu div if user clicks outside of it. To test this:

如果用户点击菜单div,它会隐藏菜单div。为了测试这个:

  1. Click on Menu link.
  2. 单击“菜单”链接。

  3. Click outside of the yellow div.
  4. 单击黄色div的外部。

The div should get hidden.

div应该隐藏起来。

The problem is that this does not work on iPad. Why?

问题是这在iPad上不起作用。为什么?

Here is a FIDDLE.

这是一个FIDDLE。

I have added click touch and also tried touchend and touchstart.

我添加了点击触摸,还尝试了touchend和touchstart。

1 个解决方案

#1


2  

Got a message:

得到消息:

Comments may only be edited for 5 minutes

评论只能编辑5分钟

So I'll post it as an answer instead.

所以我会把它作为答案发布。

  • I suggest using touchend in your tests, the touch event does not exist. Maybe your tests failed because of browser cache?
  • 我建议在测试中使用touchend,触摸事件不存在。也许您的测试因浏览器缓存而失败?

  • Have you also tried putting the listener on document.documentElement, document.body and/or window?
  • 您是否也尝试将侦听器放在document.documentElement,document.body和/或window上?

  • Try vanilla JavaScript like suggested by Apple:

    试试像Apple建议的vanilla JavaScript:

    document.documentElement.addEventListener("touchend", function(e){ alert('hello world'); }, false);
    

Fiddle with document.documentElement and touchend

摆弄document.documentElement和touchend

#1


2  

Got a message:

得到消息:

Comments may only be edited for 5 minutes

评论只能编辑5分钟

So I'll post it as an answer instead.

所以我会把它作为答案发布。

  • I suggest using touchend in your tests, the touch event does not exist. Maybe your tests failed because of browser cache?
  • 我建议在测试中使用touchend,触摸事件不存在。也许您的测试因浏览器缓存而失败?

  • Have you also tried putting the listener on document.documentElement, document.body and/or window?
  • 您是否也尝试将侦听器放在document.documentElement,document.body和/或window上?

  • Try vanilla JavaScript like suggested by Apple:

    试试像Apple建议的vanilla JavaScript:

    document.documentElement.addEventListener("touchend", function(e){ alert('hello world'); }, false);
    

Fiddle with document.documentElement and touchend

摆弄document.documentElement和touchend