我創建了一個下拉菜單,打開和關閉時,我點擊其父李元素。但是當我把代碼關閉時,當用戶點擊菜單外,這使得點擊父李不再關閉菜單,但只打開它。如何讓我的下拉菜單打開/關閉,當我點擊其父或外
這是html代碼:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<ul class="menu">
<li><a href="#">Home</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">Courses</a>
<ul class="dropdown-menu">
<li><a href="#">JavaScript</a></li>
<li><a href="#">Php</a></li>
<li><a href="#">Java</a></li>
<li><a href="#">Python</a></li>
</ul>
</li>
</ul>
</body>
</html>
這是CSS:
*{padding: 0;margin: 0}
li{list-style-type: none}
.menu{background: #333;display: block}
.menu:after, .menu:before{content: '';display: table;clear: both}
.menu>li{display: inline-block;float: left}
.menu a{display: block;text-decoration: none;color: #f9f9f9;padding: 6px 10px;background: #333}
.menu a:hover{ background: #000; }
.dropdown-menu{position: absolute;max-height: 0;overflow: hidden;transition: max-height 1s ease}
.open .dropdown-menu{max-height: 30rem}
和jQuery:
(function($){
$('.dropdown-toggle').on('click', function(e){
$(this).parent().toggleClass('open');
$(this).parent().siblings().removeClass('open');
});
// This code to hide the dropdown menu
// when the user click outside the menu
$(document).on('mouseup', function(e){
$(".dropdown-menu").each(function(index) {
if(e.target !== $(this)) {
$(this).parent().removeClass('open');
}
});
});
})(jQuery);
你的代碼似乎是工作的罰款。 https://jsfiddle.net/q5eg9cwq/ – Thangaraja
你可以檢查它並解釋問題是什麼? – Thangaraja
問題是:當你點擊一個下拉菜單時,它會打開菜單,但是當你再次點擊它關閉菜單時,它不起作用。 –