我只有一个小的下拉菜单,我希望能够做到这一点,当我点击其中一个选项(不是按钮,而只是当你将鼠标悬停在菜单上时所获得的菜单)下拉菜单消失按钮)。我一直在寻找解决方案,但我似乎无法找到答案。
function changeType(str) {
document.getElementById("selectType").innerHTML = str;
document.getElementById("selectType").value = str;
}

.dropbtn {
background-color: #360363;
margin-bottom: 0px;
min-width: 120px;
color: white;
padding: 0px;
font-size: 0.7em;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
margin-top: 0px;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
margin-top: 0px;
min-width: 120px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 6px 16px;
text-decoration: none;
display: block;
margin-top: 0px;
}
.dropdown-content a:hover {
background-color: #f1f1f1
}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #4B0082;
transition: 0.5s;
}

<div class="dropdown">
<button id="selectType" class="dropbtn" value="Choose Color">Choose Color</button>
<div class="dropdown-content">
<a onclick="changeType('Red')" href="#">Red</a>
<a onclick="changeType('Green')" href="#">Green</a>
</div>
</div>
&#13;
答案 0 :(得分:3)
您可以通过CSS实现此目的:
.dropdown:active .dropdown-content,
.dropdown:focus .dropdown-content {
display: none;
}
段:
function changeType(str) {
document.getElementById("selectType").innerHTML = str;
document.getElementById("selectType").value = str;
}
.dropbtn {
background-color: #360363;
margin-bottom: 0px;
min-width: 120px;
color: white;
padding: 0px;
font-size: 0.7em;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
margin-top: 0px;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
margin-top: 0px;
min-width: 120px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 6px 16px;
text-decoration: none;
display: block;
margin-top: 0px;
}
.dropdown-content a:hover {
background-color: #f1f1f1
}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #4B0082;
transition: 0.5s;
}
.dropdown:active .dropdown-content,
.dropdown:focus .dropdown-content {
display: none;
}
<div class="dropdown">
<button id="selectType" class="dropbtn" value="Choose Color">Choose Color</button>
<div class="dropdown-content">
<a onclick="changeType('Red')" href="#">Red</a>
<a onclick="changeType('Green')" href="#">Green</a>
</div>