单击外部菜单以关闭jQuery

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


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


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


$(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()想法,认为它会触发菜单上没有的任何东西,但是没有用。


月关宝盒
浏览 434回答 3
3回答

互换的青春

将单击事件附加到关闭窗口的文档主体。将单独的click事件附加到窗口,该事件将停止传播到文档主体。$('html').click(function() {&nbsp; //Hide the menus if visible});$('#menucontainer').click(function(event){&nbsp; &nbsp; event.stopPropagation();});

慕勒3428872

答案是正确的,但它将添加一个侦听器,该侦听器将在您的页面上每次单击时触发。为了避免这种情况,您可以只添加一次侦听器:$('a#menu-link').on('click', function(e) {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; e.stopPropagation();&nbsp; &nbsp; $('#menu').toggleClass('open');&nbsp; &nbsp; $(document).one('click', function closeMenu (e){&nbsp; &nbsp; &nbsp; &nbsp; if($('#menu').has(e.target).length === 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#menu').removeClass('open');&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(document).one('click', closeMenu);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });});编辑:如果您要避免stopPropagation()使用初始按钮,可以使用此按钮var $menu = $('#menu');$('a#menu-link').on('click', function(e) {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; if (!$menu.hasClass('active')) {&nbsp; &nbsp; &nbsp; &nbsp; $menu.addClass('active');&nbsp; &nbsp; &nbsp; &nbsp; $(document).one('click', function closeTooltip(e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($menu.has(e.target).length === 0 && $('a#menu-link').has(e.target).length === 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $menu.removeClass('active');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else if ($menu.hasClass('active')) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(document).one('click', closeTooltip);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; $menu.removeClass('active');&nbsp; &nbsp; }});

开满天机

如果您可以使用插件,那么我建议Ben Alman位于此处的clickoutside插件:它的用法很简单:$('#menu').bind('clickoutside', function (event) {&nbsp; &nbsp; $(this).hide();});希望这可以帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JQuery