[英]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.