Aquí estoy tratando de ocultar el bloque, pero por primera vez necesito hacer doble clic en el botón cada vez que se actualiza la página. He adjuntado mi código a continuación como referencia.
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> #myDIV { width: 100%; padding: 50px 0; text-align: center; background-color: lightblue; margin-top: 20px; display: none; } </style> </head> <body> <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p> <button onclick="myFunction()">Try it</button> <div id="myDIV"> This is my DIV element. </div> <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p> <script> function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display == "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> </body> </html>¿Por qué es eso y alguien puede decirme dónde estoy cometiendo un error?
Con el primer clic, el elemento div no se encuentra en la página, ya que el CSS hace que se display: none . Entonces, el primer bloqueo si no se está llevando a cabo. Establece la display del elemento como none en el primer clic y en el segundo clic cambia el valor a block .
Por lo tanto, debemos verificar si el valor del atributo de display es none o "" en el primer clic.
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> #myDIV { width: 100%; padding: 50px 0; text-align: center; background-color: lightblue; margin-top: 20px; display: none; } </style> </head> <body> <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p> <button onclick="myFunction()">Try it</button> <div id="myDIV"> This is my DIV element. </div> <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p> <script> function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display === "none" || x.style.display === "") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> </body> </html>Bastante similar a la respuesta de @arsho, puede definir su CSS en línea como display:none primero.
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> #myDIV { width: 100%; padding: 50px 0; text-align: center; background-color: lightblue; margin-top: 20px; } </style> </head> <body> <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p> <button onclick="myFunction()">Try it</button> <div id="myDIV" style="display: none;">This is my DIV element.</div> <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p> <script> function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display == "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> </body> </html>Como se explica en esta respuesta en SO , solo el estilo en línea o el estilo aplicado al elemento como un atributo del elemento como <div style="diplay:none;"></div> aparecerá cuando acceda al element.style Debe acceder a computedStyle para aplicar el estilo en el elemento desde cualquier parte del documento.
Para obtener el computedStyle de un elemento, puede usar:
window.getComputedStyle(element).displayEntonces, se supone que su código JS debe verse así:
function myFunction() { var x = document.getElementById("myDIV"); console.log(typeof x) console.log(window.getComputedStyle(x).display) if (window.getComputedStyle(x).display == "none") { x.style.display = "block"; } else { x.style.display = "none"; } }Pruébalo aquí mismo:
function myFunction() { var x = document.getElementById("myDIV"); if (window.getComputedStyle(x).display == "none") { x.style.display = "block"; } else { x.style.display = "none"; } } #myDIV { width: 100%; padding: 50px 0; text-align: center; background-color: lightblue; margin-top: 20px; display:none; } <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p> <button onclick="myFunction()">Try it</button> <div id="myDIV"> This is my DIV element. </div> <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>El problema es que inicialmente style.display no está configurado en nada (el estilo en línea no se ha configurado).
Entonces, en lugar de probar 'ninguno', prueba NO 'bloquear'. De esa manera, la prueba se logrará incluso en la primera vez.
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> #myDIV { width: 100%; padding: 50px 0; text-align: center; background-color: lightblue; margin-top: 20px; display: none; } </style> </head> <body> <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p> <button onclick="myFunction()">Try it</button> <div id="myDIV"> This is my DIV element. </div> <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p> <script> function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display != "block") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> </body> </html>Un enfoque elegante sería simplemente usar la función de alternancia. Solo necesita agregar una clase oculta que puede alternar.
function myFunction() { var x = document.getElementById("myDIV"); x.classList.toggle('hide'); } #myDIV { width: 100%; padding: 50px 0; text-align: center; background-color: lightblue; margin-top: 20px; } .hide { display: none; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> </style> </head> <body> <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p> <button onclick="myFunction()">Try it</button> <div id="myDIV" class="hide"> This is my DIV element. </div> <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p> <script> </script> </body> </html>