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

时间:2014-04-18 10:47:40

标签: javascript jquery html css drop-down-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();
});

3 个答案:

答案 0 :(得分:1)

Working Fiddle

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

this answer

的帮助下

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

使用您提供的信息和codepen我看不到它的工作原理,但我认为$(document).click(要隐藏的function()不起作用,因为下拉文件在文档中,所以当你点击它,它就会消失。我建议你看看这篇文章How to hide/show drop down list content in HTML