簡體   English   中英

如何單擊一次 function 運行?

[英]How to click once for a function to run?

我希望我的函數(dropFunction(),這使得 div #dropdownList 出現)在第一次單擊我的按鈕(#drop-btn)時運行,但是,我必須單擊它兩次才能運行 function,但只有第一次時間。 第一次雙擊后,它會正常運行。 我如何使它在第一次點擊時運行,而不是第一次點擊第二次? 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>

您必須使用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>

您可以使用 2 種解決方案。

1.

if(x.style.display === "無")

=>

if(window.getComputedStyle(x).display === "none")

或者

2.

<div id="dropdownList">

=>

<div id="dropdownList" style="display: none;">

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM