【问题标题】:How to click once for a function to run?如何单击一次以运行功能?
【发布时间】:2020-11-14 02:01:42
【问题描述】:
我希望我的函数(dropFunction(),它使 div #dropdownList 出现)在第一次单击我的按钮 (#drop-btn) 时运行,但是,我必须单击它两次才能运行该函数,但是只有第一次。第一次双击后,它会正常运行。我如何让它在第一次点击时运行,而不是第一次点击第二次?
CSS:
function dropFunction() {
var x = document.getElementById("dropdownList")
if (x.style.display === "none") {
x.style.display = "block"
} else {
x.style.display = "none"
}
}
#dropdownList {
display:none;
}
<div class="dropdown">
<button onclick = "dropFunction()" class="drop-btn">Menu</button>
<div id="dropdownList">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
【问题讨论】:
标签:
javascript
function
button
onclick
display
【解决方案1】:
您可以使用 2 种解决方案。
1.
if(x.style.display === "none")
=>
if(window.getComputedStyle(x).display === "none")
或
2.
=>
function dropFunction() {
var x = document.getElementById("dropdownList")
if (window.getComputedStyle(x).display === "none") {
x.style.display = "block"
} else {
x.style.display = "none"
}
}
#dropdownList {
display:none;
}
<div class="dropdown">
<button onclick = "dropFunction()" class="drop-btn">Menu</button>
<div id="dropdownList">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
function dropFunction() {
var x = document.getElementById("dropdownList")
if (x.style.display === "none") {
x.style.display = "block"
} else {
x.style.display = "none"
}
}
#dropdownList {
display:none;
}
<div class="dropdown">
<button onclick = "dropFunction()" class="drop-btn">Menu</button>
<div id="dropdownList" style="display:none;">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
【解决方案2】:
您必须使用 window.getComputedStyle(x) 从 CSS 中获取值
function dropFunction() {
var x = document.getElementById("dropdownList")
if (window.getComputedStyle(x).display === "none") {
x.style.display = "block"
} else {
x.style.display = "none"
}
}
#dropdownList {
display:none;
}
<div class="dropdown">
<button onclick = "dropFunction()" class="drop-btn">Menu</button>
<div id="dropdownList">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>