[英]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.