gpt4 book ai didi

javascript - 仅使用 JavaScript 在导航栏外部单击后关闭下拉菜单?

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

我想制作一个非常简单的下拉菜单,当点击导航之外时它会自动隐藏。注意我已经制作了下拉菜单但是......我不明白如何关闭它。这是我的 HTML 和 JavaScript 代码。

<section class="dropdownone">
<div class="container">
<h1>Dropdown One</h1>
<li class="MajorDropOne">
<a href="#">
<button type="button"
class="btn btn-primary dropOnebtn">Click Dropdown</button>
</a>
<ul class="dropOne">
<li>home</li>
<li>about</li>
<li>profile</li>
</ul>
</li>
</div>
</section>

最佳答案

使用 JavaScript :

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}

.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}

.dropdown {
position: relative;
display: inline-block;
}

.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}

.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}

.dropdown a:hover {background-color: #ddd;}

.show {display: block;}
</style>
</head>
<body>

<h2>Clickable Dropdown</h2>
<p>Click on the button to open the dropdown menu.</p>

<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Profile</a>
</div>
</div>

<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {

var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>

</body>
</html>

关于javascript - 仅使用 JavaScript 在导航栏外部单击后关闭下拉菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51149337/

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