简体   繁体   English

我想使用 javascript 隐藏一个 div

[英]I want to hide a div using javascript

I created a div contaning a form and a button.我创建了一个包含表单和按钮的 div。 I want to hide the entire div when the button is clicked.我想在单击按钮时隐藏整个 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>

This is what I tried to do, however when I click the button, the div disappears for a split second then reappears again.这就是我尝试做的,但是当我单击按钮时,div 消失了一瞬间然后再次出现。 When I removed the button from the div it worked just fine.当我从 div 中删除按钮时,它工作得很好。 How can I make it disappear for good?我怎样才能让它永远消失?

you have document.querySelecor('div') which is selecting the first <div> in the whole document, probably not what you want.你有document.querySelecor('div') ,它选择了整个文档中的第一个<div> ,可能不是你想要的。

the error is here错误在这里

function myFunction() {
    let x = document.querySelector("div");
    if (x.style.display == "none") { // error
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

you can only set a style, not get a style.您只能设置样式,而不能获取样式。 Why?为什么? Because reasons nobody with common sense will understand.因为任何有常识的人都不会理解的原因。 so instead you have to use getComputedStyle(element).styleName所以你必须使用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";
    }
}

but as mentioned in a comment above, toggling a class and using event listeners are much better practice但正如上面的评论所述,切换 class 并使用事件监听器是更好的做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM