![](/img/trans.png)
[英]when i click on checkbox then i want to show or hide a div using bootstrap and javascript
[英]I want to hide a div using javascript
我創建了一個包含表單和按鈕的 div。 我想在單擊按鈕時隱藏整個 div。
function myFunction() { let x = document.querySelector("div"); if (x.style.display == "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
<div onmouseover="firstPageDisplay();" id="firstPage"> <div><img id="imgs"></div> <div class="center"> <form class="center">Authentification<br> <p>Login</p> <input id="login" type="text"><br> <p>Password</p> <input id="password" type="password"><br><br> <button onclick="myFunction();" id="btnA">Se connecter</button> </form> </div> </div>
這就是我嘗試做的,但是當我單擊按鈕時,div 消失了一瞬間然后再次出現。 當我從 div 中刪除按鈕時,它工作得很好。 我怎樣才能讓它永遠消失?
你有document.querySelecor('div')
,它選擇了整個文檔中的第一個<div>
,可能不是你想要的。
錯誤在這里
function myFunction() {
let x = document.querySelector("div");
if (x.style.display == "none") { // error
x.style.display = "block";
} else {
x.style.display = "none";
}
}
您只能設置樣式,而不能獲取樣式。 為什么? 因為任何有常識的人都不會理解的原因。 所以你必須使用getComputedStyle(element).styleName
function myFunction() {
let x = document.querySelector("div"); // if this is div you want
if (getComputedStyle(x).display == "none") { // 👍👍👍
x.style.display = "block";
} else {
x.style.display = "none";
}
}
但正如上面的評論所述,切換 class 並使用事件監聽器是更好的做法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.