将鼠标悬停在div(Selector
)上时,会显示一个下拉列表。单击元素时,将调用JS函数并执行多个任务。没关系。我的问题是我希望下拉后的下拉列表消失,但不能使用.style.display= "none"
,因为我希望它再次悬停在Selector
上时显示上传。
我不熟悉JQuery,所以对普通JS感觉更舒服。
function TheJSFunction(What) {
//alert (What);
// First try: remove classes to dropdown, and then add class 'dropdown-content' (vis: hidden and opacity 0):
// document.getElementById("dc").className = '';
// document.getElementById("dc").classList.add('dropdown-content');
// Second try: set opacity to 0 (or visibility to hidden)
// But then dropdown is not displayed again when hovering over Selector:
//document.getElementById("dc").style.opacity = 0;
}
.Selector {
display: inline;
float: left;
padding: 8px;
background: #282828;
color: #ffffff;
width: 300px;
text-align: center;
}
.Selector:hover {
background-color: #800000;
transition: all 0.5s ease;
}
.dropdown-content {
visibility: hidden;
opacity: 0;
position: absolute;
background-color: #ff8080;
margin-top: 8px;
margin-left: -8px;
width: 316px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.4);
z-index: 1;
}
.Selector:hover .dropdown-content {
visibility: visible;
opacity: 1;
transition: all 0.5s ease;
}
.dropdown-content .DD_content {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
cursor: pointer;
}
.dropdown-content .DD_content:hover {
background-color: #ffb3b3;
transition: all 1s ease;
}
<div class="Selector">Lizards
<div class="dropdown-content" id="dc">
<div class="DD_content" onclick="TheJSFunction('New');">New Specie</div>
<div class="DD_content" onclick="TheJSFunction('Edit');">Edit record</div>
</div>
</div>
答案 0 :(得分:2)
你可以将onmouseover添加到div
<div class="Selector" onmouseover="reset()">Lizards
<div class="dropdown-content" id="dc">
<div class="DD_content" onclick="TheJSFunction('New');">New Specie</div>
<div class="DD_content" onclick="TheJSFunction('Edit');">Edit record</div>
</div>
</div>
然后添加一个函数将不透明度重置为100
function reset() {
document.getElementById("dc").style.opacity = 100;
}
答案 1 :(得分:0)
为了有效地做到这一点,你需要做一些JS来做到这一点。您可以在单击时添加类或设置visibility属性,等待onmouseout
事件,然后删除类/属性以重置它。这甚至适用于触摸设备。
示例代码:
var dropdown = document.querySelector(".dropdown-content");
dropdown.addEventListener("click", function() {
dropdown.style.visibility = "hidden";
});
dropdown.addEventListener("mouseout", function() {
dropdown.style.visibility = "";
});
编辑:
作为奖励,您可以轻松地在同一行中切换属性。由于这些东西导致DOM重排,它应该意味着如果它是通过CSS选择器控制它不应该显示备份。所以只是......
function ClickHandler(element) {
element.style.visibility = "none";
element.style.visibility = "";
}
答案 2 :(得分:0)
您需要添加一个事件监听器来覆盖&#39; TheJSFunction&#39;中指定的不透明度。功能
document.getElementsByClassName('Selector')[0].addEventListener("mouseover", function(){
document.getElementById("dc").style.opacity=1;
});