简体   繁体   English

单击触摸设备(iPad / iPhone)上的任意位置以隐藏由.hover()切换的下拉菜单

[英]Click anywhere on touch device (iPad/iPhone) to hide dropdown that is toggled by .hover()

I have a dropdown menu that is displayed when the user hovers over a nav link. 当用户将鼠标悬停在导航链接上时,会显示一个下拉菜单。 This is being triggered in jQuery with .hover(). 这是使用.hover()在jQuery中触发的。 The opening and closing of this dropdown works fine on touch devices when the user clicks the nav link (iPad/iPhone), but I am trying to hide the dropdown when the user clicks anywhere else on the page. 当用户单击导航链接(iPad / iPhone)时,此下拉列表的打开和关闭在触摸设备上工作正常,但是当用户单击页面上的任何其他位置时,我试图隐藏该下拉列表。

Here is a link to my JSFiddle with a basic setup. 这是基本设置到我的JSFiddle的链接。

I have found ways of doing this with .click(), but not .hover(). 我已经找到了使用.click()而不是.hover()的方法。

This is my basic jQuery code: 这是我的基本jQuery代码:

$('.hoverItem').hover(function(e) {
  $('.dropdown').toggleClass('visible');
  e.stopPropagation()
});

Why not make the body clickable, and hide the dropdown when it is clicked like this? 为什么不使主体可单击,并在像这样单击时隐藏下拉菜单?

HTML: HTML:

<body id="clickArea">
<div class="hoverItem">Hover here to show dropdown</div>
<div class="dropdown">Dropdown Area</div>
</body>

JS: JS:

$('.hoverItem').hover(function(e) {
$('.dropdown').toggleClass('visible');
});

$('#clickArea').click(function(e) {
$('.dropdown').toggleClass('visible');
});

jsfiddle jsfiddle

First, it is far better, imho, to use: 首先,恕我直言,使用:

.on(click, function(e))

vs

.hover(function(e))

Next, would be an if / else statement. 接下来,将是一个if / else语句。

var navcheck = $(this).attr(class);
if(navcheck!=dropdown){ $(.dropdown).hide(); } else { $(dropdown).show(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM