CSS下拉列表在第一次单击时未打开



我用纯HTML、CSS和JavaScript创建了一个下拉菜单。它的工作原理应该是,每当我点击指定的按钮时,下拉列表就会打开。

但是,当我第一次点击按钮时,它不会打开。当我在第一次点击后点击它时,它工作得很好。

为了更好地理解,我附上了一个代码片段。

function showDrp() {
var dropdown = document.getElementById("dropdown");
var drpbutn = document.getElementById("drpbutn");
if (dropdown.style.display === "none") {
dropdown.style.display = "block";
drpbutn.innerHTML = "DROPDOWN ▴";
} else {
dropdown.style.display = "none";
drpbutn.innerHTML = "DROPDOWN ▾";
}
}
.upper-cont {
width: 30%; 
height: 30%;
position: absolute; 
cursor: pointer; 
background-color: blue; 
color: white; 
text-align: center;
}

.upper-cont:hover { background-color: #dfdfdf; color: blue;}
.dropdown {
background-color: #4A4A4A;
color: white;
position: fixed;
top: 30%;
left: 0%;
width: 100%;
height: 50%;
display: none;
}
<html>
<body>
<div class="upper-cont" style="margin-left: 40%;" onclick="showDrp()"><h3 id="drpbutn">DROPDOWN &#x25BE;</h3></div>
<div class="dropdown" id="dropdown">This is a dropdown</div>
</body>
</html>

dropdown.style.display的初始值不等于"none",并且由于脚本将"none"以外的任何内容视为可见,因此将下拉列表的初始状态视为下拉列表已显示。

解决这个问题的一个简单方法是修改if条件:

function showDrp() {
var dropdown = document.getElementById("dropdown");
var drpbutn = document.getElementById("drpbutn");
if (dropdown.style.display !== "block") {
dropdown.style.display = "block";
drpbutn.innerHTML = "DROPDOWN &#x25B4;";
} else {
dropdown.style.display = "none";
drpbutn.innerHTML = "DROPDOWN &#x25BE;";
}
}
.upper-cont {
width: 30%; 
height: 30%;
position: absolute; 
cursor: pointer; 
background-color: blue; 
color: white; 
text-align: center;
}

.upper-cont:hover { background-color: #dfdfdf; color: blue;}
.dropdown {
background-color: #4A4A4A;
color: white;
position: fixed;
top: 30%;
left: 0%;
width: 100%;
height: 50%;
display: none;
}
<html>
<body>
<div class="upper-cont" style="margin-left: 40%;" onclick="showDrp()"><h3 id="drpbutn">DROPDOWN &#x25BE;</h3></div>
<div class="dropdown" id="dropdown">This is a dropdown</div>
</body>
</html>

使用jQuery这很容易。请尝试此解决方案

function showDrp() {        
$("#dropdown").toggle();
$("#drpbutn span").toggleClass("caret-up");
}
.upper-cont {
width: 30%; 
height: 30%;
position: absolute; 
cursor: pointer; 
background-color: blue; 
color: white; 
text-align: center;
}

.upper-cont:hover { background-color: #dfdfdf; color: blue;}
.dropdown {
background-color: #4A4A4A;
color: white;
position: fixed;
top: 30%;
left: 0%;
width: 100%;
height: 50%;
display: none;
}
<html>
<body>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="upper-cont" style="margin-left: 40%;" onclick="showDrp()"><h3 id="drpbutn">DROPDOWN <span class="caret"></span></h3></div>
<div class="dropdown" id="dropdown">This is a dropdown</div>
</body>
</html>

最新更新