我编写了一个脚本,当单击它时,弹出div并将活动类分配给适当的父元素。我还添加了一些功能,当在div下拉列表外单击它时会关闭它。不幸的是,通过在任何元素上的下拉分隔符内部单击它也是隐藏的。如何解决此问题,以便下拉列表中间的项目的可点击性不会影响它?
$(document).click(function() {
$("#dropdown").slideUp("fast");
$(".dropdown-parent").removeClass("active");
});
$(document).on("click", ".dropdown-parent:not(.active)", function(e) {
e.stopPropagation();
$(".dropdown-parent").removeClass("active");
$(this).addClass("active");
$("#dropdown").slideDown("fast");
});
$(document).on("click", ".dropdown-parent.active", function() {
$("#dropdown").slideToggle("fast");
$(this).removeClass("active");
});
.active {
background: red;
color: #fff;
}
#dropdown {
display: none;
background: black;
height: 400px;
width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="dropdown-parent">test</a>
<a href="#" class="dropdown-parent">test2</a>
<a href="#" class="dropdown-parent">test3</a>
<a href="#" class="dropdown-parent">test4</a>
<div id="dropdown" class="container">
<a href="#">test in dropdown</a>
<p style="color: white">test2 in dropdown</p>
</div>
答案 0 :(得分:1)
您可以停止.container
内的点击:
$(document).on("click", ".container", function(e) {
e.stopPropagation();
});
$(document).click(function() {
$("#dropdown").slideUp("fast");
$(".dropdown-parent").removeClass("active");
});
$(document).on("click", ".dropdown-parent:not(.active)", function(e) {
e.stopPropagation();
$(".dropdown-parent").removeClass("active");
$(this).addClass("active");
$("#dropdown").slideDown("fast");
});
$(document).on("click", ".dropdown-parent.active", function() {
$("#dropdown").slideToggle("fast");
$(this).removeClass("active");
});
$(document).on("click", ".container", function(e) {
e.stopPropagation();
});
&#13;
.active {
background: red;
color: #fff;
}
#dropdown {
display: none;
background: black;
height: 400px;
width: 400px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="dropdown-parent">test</a>
<a href="#" class="dropdown-parent">test2</a>
<a href="#" class="dropdown-parent">test3</a>
<a href="#" class="dropdown-parent">test4</a>
<div id="dropdown" class="container">
<a href="#">test in dropdown</a>
<p style="color: white">test2 in dropdown</p>
</div>
&#13;