单击外部菜单以在jQuery中关闭 [英] Click outside menu to close in jquery

查看:62
本文介绍了单击外部菜单以在jQuery中关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,根据业务需求,我有一个单击显示的下拉菜单.将鼠标移开菜单后,该菜单将再次隐藏.

So I have a drop-down menu that shows on a click, as per business requirements. The menu becomes hidden again after you mouse away from it.

但是现在我被要求将其保留在原处,直到用户单击文档上的任何位置.如何做到这一点?

But now I am being asked to have it stay in place until user clicks anywhere on the document. How can this be accomplished?

这是我现在所拥有的简化版本:

This is a simplified version of what I have now:

$(document).ready(function() {
  $("ul.opMenu li").click(function(){
   $('#MainOptSubMenu',this).css('visibility', 'visible');
  });

  $("ul.opMenu li").mouseleave(function(){
      $('#MainOptSubMenu',this).css('visibility', 'hidden');
  });
});



<ul  class="opMenu">
  <li id="footwo" class="">
    <span id="optImg" style="display: inline-block;"> <img src="http://localhost.vmsinfo.com:8002/insight/images/options-hover2.gif"/> </span>
      <ul id="MainOptSubMenu" style="visibility: hidden; top: 25px; border-top: 0px solid rgb(217, 228, 250); background-color: rgb(217, 228, 250); padding-bottom: 15px;">
        <li>some</li>
       <li>nav</li>
       <li>links</li>
       </ul>
    </li>
</ul> 

我尝试了类似$('document[id!=MainOptSubMenu]').click(function()这样的操作,认为它会在菜单之外的任何内容上触发,但没有用.

I tried something like this $('document[id!=MainOptSubMenu]').click(function() thinking it would trigger on anything that wasnt the menu, but it didnt work.

推荐答案

看看此问题使用的方法:

Take a look at the approach this question used:

如何检测元素外部的点击?

将单击事件附加到关闭窗口的文档主体.将单独的click事件附加到窗口,以停止传播到文档主体.
Attach a click event to the document body which closes the window. Attach a separate click event to the window which stops propagation to the document body.

$('html').click(function() {
  //Hide the menus if visible
});

$('#menucontainer').click(function(event){
    event.stopPropagation();
});

这篇关于单击外部菜单以在jQuery中关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆