简体   繁体   中英

I want to hide a div using javascript

I created a div contaning a form and a button. I want to hide the entire div when the button is clicked.

 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. When I removed the button from the div it worked just fine. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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