[英]How do I get my code to close the dropdown menu when the user clicks “Category” while it's already opened?
點擊“類別”以打開菜單。 現在,如果再次單擊“類別”,則預期結果將是菜單關閉。 相反,它關閉了,但隨后又迅速打開了! 我在代碼中找不到導致此錯誤的原因。 請協助。
我以為在ActiveListItem上具有“ slideToggle”(除非選擇了其他項,否則ActiveListItem =“ Category”)將是正確的代碼,但是它不起作用。
HTML
<div id="navbarcontainer">
<ul class="navbar">
<li>
<span class="ActiveListItem">Category</span>
<ul>
<li><span>Music</span></li>
<li><span>Movie</span></li>
<li><span>Book</span></li>
<li><span>TV</span></li>
<li><span>Game</span></li>
<li><span>Activity</span></li>
<li><span>Misc</span></li>
</ul>
</li>
</ul>
</div>
CSS
#navbarcontainer{
vertical-align:top;
display:inline-block;
}
/* navbar */
ul.navbar {
border-style:solid;
border-width:1px;
border-color:#739FE0;
width:100px;
border-radius:4px;
height:33px;
}
ul.navbar li span.ActiveListItem {
background:url("http://i.imgur.com/p0qeihf.png") !important;
background-repeat:no-repeat !important;
background-size:10px 10px !important;
background-position:83px 13px !important;
color:white; !important;
background-color:#222 !important;
padding:7.5px 0px !important;
font-weight:normal !important;
border-radius:4px;
height:18px;
width:100px;
margin-bottom:1px;
}
ul.navbar li {
z-index:101;
position:relative;
width:100px;
}
ul.navbar li span {
display:block;
color:white;
padding:10px 5px;
text-decoration:none;
transition:all .1s ease-in;
}
ul.navbar li span:hover,
ul.navbar li:hover > span {
background:#739FE0;
color:#FFFFFF;
cursor:pointer;
}
ul.navbar li ul {
margin-top:0px;
background:#222;
display:none;
box-shadow:inset 0 0px 3px rgba(0,0,0,.6),
0 5px 10px rgba(0,0,0,.6);
}
ol, ul { list-style:outside none none; }
jQuery的
var container = $('.navbar');
$(document).on('click', '.ActiveListItem', function(event) {
$('.navbar li ul').slideToggle(300);
$('.navbar > li:first-child > span').text("Category");
});
$(document).on('click', '.navbar ul span', function(event) {
$("#input1").focus();
$('.navbar li ul').slideUp(300);
$('.navbar > li:first-child > span').text($(this).text());
});
$(document).mouseup(function (e) {
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$('.navbar li ul').slideUp(300);
}
});
只需在toogle事件之前添加stop()
:
$(document).on('click', '.ActiveListItem', function(event) {
$('.navbar li ul').stop().slideToggle(300);
$('.navbar > li:first-child > span').text("Category");
});
請找到FIDDLE更新
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.