Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

288
Visualizações
Ocultar y mostrar la etiqueta Div en HTML

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?

over 4 years ago · Santiago Trujillo
5 Respostas
Responde à pergunta

0

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>

over 4 years ago · Santiago Trujillo Relatório

0

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>

over 4 years ago · Santiago Trujillo Relatório

0

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).display

Entonces, 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>

over 4 years ago · Santiago Trujillo Relatório

0

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>

over 4 years ago · Santiago Trujillo Relatório

0

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>

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda