Javascript出现消失动画不起作用



我想让h1消失,3秒后再次出现。它消失了,但不再出现。或者我需要内联样式吗?除了如果,还有其他有用的循环吗?

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>

在现代浏览器中,您不需要JavaScript。带有关键帧的CSS动画完全能够提供相同的效果:

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

您可能需要调整时间。在这篇精彩的文章中了解更多关于CSS关键帧动画的信息-https://www.joshwcomeau.com/animation/keyframe-animations/

您可以使用setTimeout执行一次。

const h1 = document.querySelector('h1');
h1.style.display = 'none';
setTimeout(() => h1.style.display = 'block', 3000);

或者您可以使用setInterval每3秒执行一次。

const h1 = document.querySelector('h1');
function switchDisplay() {
if (h1.style.display === 'block') h1.style.display = 'none';
else h1.style.display = 'block';
}
setInterval(switchDisplay, 3000);

最新更新