Quiero hacer que h1 desaparezca y después de 3 segundos vuelva a aparecer. Desaparece pero no vuelve a aparecer. ¿O necesito un estilo en línea para ello? ¿Y cualquier otro bucle útil para esto, excepto si?
let head1 = document.querySelector(".asd") let head1style = getComputedStyle(head1); let head1disp = head1style.display; let changedisp = function() { if (head1disp === "block") { head1.style.display = "none"; } else if (head1disp === "none") { head1.style.display = "block" } else { console.log("Something Wrong!") } }; setInterval(changedisp, 3000); h1 { display: block; } <body> <h1 class="asd">Look at me!</h1> <script src="app.js"></script> </body> </html>No necesita JavaScript para eso en un navegador moderno. Las animaciones CSS con fotogramas clave son totalmente capaces de ofrecer el mismo efecto:
<style> @keyframes fade-out-in { 0% { opacity: 1; } 25% { opacity: 0; } 75% { opacity: 0; } 100% { opacity: 1; } } .box { animation: fade-out-in 5000ms; /* wait time at the beginning */ animation-delay: 2000ms; } </style> <div class="box"> Hello World </div>Probablemente necesitará ajustar el tiempo. Obtenga más información sobre las animaciones de fotogramas clave CSS en este fantástico artículo: https://www.joshwcomeau.com/animation/keyframe-animations/
Puede usar setTimeout para hacerlo una vez.
const h1 = document.querySelector('h1'); h1.style.display = 'none'; setTimeout(() => h1.style.display = 'block', 3000); O puede usar setInterval para hacerlo cada 3 segundos.
const h1 = document.querySelector('h1'); function switchDisplay() { if (h1.style.display === 'block') h1.style.display = 'none'; else h1.style.display = 'block'; } setInterval(switchDisplay, 3000);