Programming

jquery에서 닫으려면 메뉴 외부를 클릭하십시오.

procodes 2020. 8. 8. 14:04
반응형

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()메뉴가 아닌 모든 것을 트리거 할 것이라고 생각하는 것과 같은 것을 시도했지만 작동하지 않았습니다.


이 질문에서 사용한 접근 방식을 살펴보십시오.

요소 외부의 클릭을 어떻게 감지합니까?

창을 닫는 문서 본문에 클릭 이벤트를 첨부하십시오. 문서 본문으로의 전파를 중지하는 별도의 클릭 이벤트를 창에 첨부하십시오.
$('html').click(function() {
  //Hide the menus if visible
});

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


정답은 맞지만 페이지에서 클릭이 발생할 때마다 트리거되는 리스너를 추가합니다. 이를 방지하려면 리스너를 한 번만 추가하면됩니다.

$('a#menu-link').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();

    $('#menu').toggleClass('open');

    $(document).one('click', function closeMenu (e){
        if($('#menu').has(e.target).length === 0){
            $('#menu').removeClass('open');
        } else {
            $(document).one('click', closeMenu);
        }
    });
});

편집 : stopPropagation()초기 버튼 을 피 하려면 이것을 사용할 수 있습니다.

var $menu = $('#menu');

$('a#menu-link').on('click', function(e) {
    e.preventDefault();

    if (!$menu.hasClass('active')) {
        $menu.addClass('active');

        $(document).one('click', function closeTooltip(e) {
            if ($menu.has(e.target).length === 0 && $('a#menu-link').has(e.target).length === 0) {
                $menu.removeClass('active');
            } else if ($menu.hasClass('active')) {
                $(document).one('click', closeTooltip);
            }
        });
    } else {
        $menu.removeClass('active');
    }
});

플러그인 사용이 괜찮다면 여기에있는 Ben Alman의 clickoutside 플러그인을 제안 합니다 .

사용법은 다음과 같이 간단합니다.

$('#menu').bind('clickoutside', function (event) {
    $(this).hide();
});

도움이 되었기를 바랍니다.


stopPropagation그들이 HTML 요소에 가까운 핸들러를 첨부 할 수있는 다른 메뉴를 포함하여 다른 이벤트 핸들러를 방해 할 수 있기 때문에 옵션은 엉망이다.

다음은 user2989143 의 답변을 기반으로 한 간단한 솔루션입니다 .

$('html').click(function(event) {
    if ($(event.target).closest('#menu-container, #menu-activator').length === 0) {
        $('#menu-container').hide();
    }
});

조사 할 수있는 두 가지 옵션 :

  • On showing of the menu, place a large empty DIV behind it covering up the rest of the page and give that an on-click event to close the menu (and itself). This is akin to the methods used with lightboxes where clicking on the background closes the lightbox
  • On showing of the menu, attach a one-time click event handler on the body that closes the menu. You use jQuery's '.one()' for this.

I found a variant of Grsmto's solution and Dennis' solution fixed my issue.

$(".MainNavContainer").click(function (event) {
    //event.preventDefault();  // Might cause problems depending on implementation
    event.stopPropagation();

    $(document).one('click', function (e) {
        if(!$(e.target).is('.MainNavContainer')) {
            // code to hide menus
        }
    });
});

I use this solution with multiple elements with the same behavior in the same page:

$("html").click(function(event){
    var otarget = $(event.target);
    if (!otarget.parents('#id_of element').length && otarget.attr('id')!="id_of element" && !otarget.parents('#id_of_activator').length) {
        $('#id_of element').hide();
    }
});

stopPropagation() is a bad idea, this breaks standard behaviour of many things, including buttons and links.


I have recently faced the same issue. I wrote the following code:

    $('html').click(function(e) {
      var a = e.target;
      if ($(a).parents('.menu_container').length === 0) {
        $('.ofSubLevelLinks').removeClass('active'); //hide menu item
        $('.menu_container li > img').hide(); //hide dropdown image, if any
     }
    });

It has worked for me perfectly.


what about this?

    $(this).mouseleave(function(){  
        var thisUI = $(this);
        $('html').click(function(){
                thisUI.hide();
            $('html').unbind('click');
         });
     });

I find it more useful to use mousedown-event instead of click-event. The click-event doesn't work if the user clicks on other elements on the page with click-events. In combination with jQuery's one() method it looks like this:

$("ul.opMenu li").click(function(event){

   //event.stopPropagation(); not required any more
   $('#MainOptSubMenu').show();

   // add one mousedown event to html
   $('html').one('mousedown', function(){
       $('#MainOptSubMenu').hide();
   });
});

// mousedown must not be triggered inside menu
$("ul.opMenu li").bind('mousedown', function(evt){
    evt.stopPropagation();
});

even i came across the same situation and one of my mentor put this idea across to myself.

step:1 when clicked on the button on which we should show the drop down menu. then add the below class name "more_wrap_background" to the current active page like shown below

$('.ui-page-active').append("<div class='more_wrap_background' id='more-wrap-bg'> </div>");

step-2 then add a clicks for the div tag like

$(document).on('click', '#more-wrap-bg', hideDropDown);

where hideDropDown is the function to be called to hide drop down menu

Step-3 and important step while hiding the drop down menu is that remove that class you that added earlier like

$('#more-wrap-bg').remove();

I am removing by using its id in the above code

.more_wrap_background {
  top: 0;
  padding: 0;
  margin: 0;
  background: rgba(0, 0, 0, 0.1);
  position: fixed;
  display: block;
  width: 100% !important;
  z-index: 999;//should be one less than the drop down menu's z-index
  height: 100% !important;
}

$("html").click( onOutsideClick );
onOutsideClick = function( e )
{
    var t = $( e.target );
    if ( !(
        t.is("#mymenu" ) ||     //Where #mymenu - is a div container of your menu
        t.parents( "#mymenu" ).length > 0
        )   )
    {
        //TODO: hide your menu
    }
};

And better to set the listener only when your menu is being visible and always remove the listener after menu becomes hidden.


I think you need something like this: http://jsfiddle.net/BeenYoung/BXaqW/3/

$(document).ready(function() {
  $("ul.opMenu li").each(function(){
      $(this).click(function(){
            if($(this).hasClass('opened')==false){          
                $('.opMenu').find('.opened').removeClass('opened').find('ul').slideUp();
                $(this).addClass('opened'); 
                $(this).find("ul").slideDown();
            }else{
                $(this).removeClass('opened'); 
                $(this).find("ul").slideUp();               
            }
      });
  });    
});

I hope it useful for you!


Use the ':visible' selector. Where .menuitem is the to-hide element(s) ...

$('body').click(function(){
  $('.menuitem:visible').hide('fast');
});

Or if you already have the .menuitem element(s) in a var ...

var menitems = $('.menuitem');
$('body').click(function(){
  menuitems.filter(':visible').hide('fast');
});

It doesn't have to be complicated.

$(document).on('click', function() {
    $("#menu:not(:hover)").hide();
});

참고URL : https://stackoverflow.com/questions/2868582/click-outside-menu-to-close-in-jquery

반응형