繁体   English   中英

在菜单外部单击时隐藏的下拉菜单

[英]Dropdown that hides on click outside of the menu

我有一个简单的下拉脚本,我希望它可以在菜单外部单击时隐藏所有打开的下拉菜单。 但这似乎不起作用,有人知道为什么吗?

您可以在这里找到它: 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();
});

工作小提琴

jQuery代码

$(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();
    });
});

这个答案的帮助下

您可以通过这种方式更改下拉菜单的显示属性。 这只是一个粗略的代码。

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

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

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

暂无
暂无

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

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