我正在尝试用CSS/HTML/JS加载,但是遇到了一些问题。
问题是尝试使初始屏幕以过渡效果消失,但过渡效果不适用时。
我确信我的 JavaScript 工作正常,因为它将新类not-displayed
附加到div
元素。
const splash = document.querySelector('.splash');
console.log(splash);
document.addEventListener('DOMContentLoaded', (e) => {
setTimeout(() => {
splash.classList.add('not-displayed');
}, 2000);
});
.splash {
z-index: 100000;
position: fixed;
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: #ffff;
}
//all of these code not working
.splash.not-displayed {
z-index: 20;
opacity: 0;
position: fixed;
height: 100vh;
width: 100%;
background-color: #f06c65;
transition: all 0.5298s ease-out;
-webkit-transition: all 0.5298s ease-out;
-moz-transition: all 0.5298s ease-out;
-o-transition: all 0.5298s ease-out;
}
@keyframes fadein {
to {
opacity: 1;
}
}
.fade-in {
opacity: 0;
animation: fadein 1s ease-in forwards;
}
<div class="splash">
<h1 class="fade-in">
hello
</h1>
</div>
这里有两件事,过渡和动画。首先,我删除了许多不必要的CSS代码以使事情更清晰。
您的代码按预期工作。页面加载时,"淡入"动画由fade-in
类触发。正如预期的那样,文本"hello"在一秒钟内从不透明度 0 淡入不透明度 1。
同时,您的 Javascript 会在页面加载时触发,并在两秒后将类not-displayed
添加到外部div。这将触发过渡效果,半秒后,当div 淡出时,它会将红色背景应用于div,使其恢复为不透明度 0。
我不确定你在这里具体想实现什么,但你已经连接了一个成功的过渡和动画效果。
const splash = document.querySelector('.splash');
console.log(splash);
document.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
splash.classList.add('not-displayed');
}, 2000);
});
.splash.not-displayed {
opacity: 0;
background-color: #f06c65;
transition: all 0.5298s ease-out;
}
.fade-in {
opacity: 0;
animation: fadein 1s ease-in forwards;
}
@keyframes fadein {
to {
opacity: 1;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="splash">
<h1 class="fade-in">
hello
</h1>
</div>
在你的代码中
document.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
splash.classList.add('not-displayed');
}, 2000);
});
您正在添加新类以删除.splash
,然后添加新类not-displayed
很好,除了你给
not-displayed
类opacity: 0
。
const splash = document.querySelector('.splash');
console.log(splash);
document.addEventListener('DOMContentLoaded', (e) => {
setTimeout(() => {
splash.classList.add('not-displayed');
}, 2000);
});
.splash {
z-index: 100000;
position: fixed;
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: #ffff;
}
.not-displayed {
z-index: 20;
/* opacity: 0; */
position: fixed;
height: 100vh;
width: 100%;
background-color: #f06c65;
transition: all 0.5298s ease-out;
-webkit-transition: all 0.5298s ease-out;
-moz-transition: all 0.5298s ease-out;
-o-transition: all 0.5298s ease-out;
}
@keyframes fadein {
to {
opacity: 1;
}
}
.fade-in {
opacity: 0;
animation: fadein 1s ease-in forwards;
}
<div class="splash">
<h1 class="fade-in">
hello
</h1>
</div>
代码笔
您应该将过渡设置为.splash
而不是.splash.not-displayed