gpt4 book ai didi

javascript - 如果用户在下拉列表外部单击,则关闭下拉列表

转载 作者:行者123 更新时间:2023-12-02 14:01:56 25 4
gpt4 key购买 nike

我有 2 个下拉按钮。如果我单击外部/或它,它会关闭,但如果我单击另一个下拉按钮,它不会关闭,另一个会弹出。我想在单击其他按钮或按钮之外的任何内容时关闭它。

function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}

function myFunction1() {
document.getElementById("myDropdown1").classList.toggle("show");
}

window.onclick = function(e) {
if (!e.target.matches('.dropbtn')) {

var dropdowns = document.getElementsByClassName("dropdown-content");
for (var d = 0; d < dropdowns.length; d++) {
var openDropdown = dropdowns[d];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<ul>
<li><a href="index.php" class="cmn-t-underline">Acasa</a></li>
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn" onclick="myFunction()" style="cursor:pointer">Infinatri firme</a>
<div class="dropdown-content" id="myDropdown">
<a href="infintare_societate_limitata.php"> Societate cu raspundere limitata (S.R.L.) </a>
</div>
</li>
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn" onclick="myFunction1()" style="cursor:pointer">Modificari firma</a>
<div class="dropdown-content" id="myDropdown1">
<a href="modificari_actualizare_date.php">Actualizare date de identificare</a>
</div>
</li>

最佳答案

您可以告诉任何点击隐藏下拉菜单,以及任何使其到达下拉菜单父级的点击停止冒泡。

/* Anything that gets to the document
/* Anything that gets to the document
will hide the dropdown */
$(document).click(function(){
$("#dropdown").hide();
});

/* Clicks within the dropdown won't make
it past the dropdown itself */
$("#dropdown").click(function(e){
e.stopPropagation();
});

关于javascript - 如果用户在下拉列表外部单击,则关闭下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40346153/

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