gpt4 book ai didi

javascript - 单击此元素的任何子元素后 Div 隐藏

转载 作者:行者123 更新时间:2023-12-03 03:05:44 24 4
gpt4 key购买 nike

我编写了一个脚本,当单击该脚本时,会弹出 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>

最佳答案

您可以停止传播 .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();
});
.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>

关于javascript - 单击此元素的任何子元素后 Div 隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47178068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com