简体   繁体   中英

Dropdown that hides on click outside of the menu

I've got a simple dropdown script and I want it to hide all open dropdowns on a click outside of the menu. But it does not seem to work, does anyone know why?

You can find it here: http://codepen.io/dr-potato/pen/rLleC?editors=101

HTML

<ul>
  <li><a href="#">Home</a></li>
  <li class="Navigation-listItem is-dropdown">
    <a href="#">About</a>
    <ul class="Navigation-list is-dropdown is-hidden">
        <li>Johnny</li>
        <li>Julie</li>
        <li>Jamie</li>
    </ul>
  </li>
  <li class="Navigation-listItem is-dropdown">
    <a href="#">Contact</a>
    <ul class="Navigation-list is-dropdown is-hidden">
        <li>Johnny</li>
        <li>Julie</li>
        <li>Jamie</li>
    </ul>
  </li>
</ul>

CSS

.Navigation-list {
    display: block;
}

.Navigation-list.is-hidden {
    display: none;
}

JS

$(document).ready(function() {
    $('.Navigation-listItem').click(function() {
      $(this).children('.Navigation-list.is-dropdown').toggleClass('is-hidden');
    });
});

/* Anything that gets to the document
   will hide the dropdown */
$(document).click(function(){
  $(".Navigation-listItem.is-dropdown").addClass('is-hidden');
});

/* Clicks within the dropdown won't make
   it past the dropdown itself */
$(".Navigation-listItem.is-dropdown").click(function(e){
  e.stopPropagation();
});

Working Fiddle

jQuery Code

$(document).ready(function () {
    $('.Navigation-listItem').click(function () {
        $(this).children('.Navigation-list.is-dropdown').toggleClass('is-hidden');
    });


    /* Anything that gets to the document
   will hide the dropdown */
    $(document).on('click', function (event) {
        if ($(event.target).closest('#menu').length == false) {
            $(".Navigation-list.is-dropdown").addClass('is-hidden');
        }
    });

    /* Clicks within the dropdown won't make
   it past the dropdown itself */
    $(".Navigation-listItem.is-dropdown ").click(function (e) {
        e.stopPropagation();
    });
});

With help from this answer

You can change the display property of your dropdown in this manner. This is just a rough code.

                       if(dropDownShow.css('display') != 'block'){
                            dropDownShow.css('display', 'block');
                            dropDownShow.css('position', 'absolute');

                        }
                        else{
                            dropDownShow.css('display', 'none');
                        }

有了您提供的信息和代码库,我看不到它起作用,但是我想隐藏的$(document).click(function()不会起作用,因为下拉列表位于文档内部,因此当您单击它时,我会建议您看这篇文章如何隐藏/显示HTML中的下拉列表内容

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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