根据页面上的一个航点,我有三个div。我试图错开这些div。我遇到的问题是因为我从不透明度中淡出它们:0,一旦添加了“动画”类,所有div都会显示(然后延迟的div将从不透明度播放动画:1)。这可能是一个愚蠢的问题,但我想不出一种方法来延迟第二和第三div的不透明度,而不必给它们单独的动画类。任何帮助将不胜感激!
.project {
opacity: 0;
}
.project.animated {
opacity: 1;
animation-name: fadeInDown;
animation-duration: 1s;
&:nth-child(2) {
animation-delay: .3s;
}
&:nth-child(3) {
animation-delay: .6s;
}
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translate3d(0, -40%, 0);
}
to {
opacity: 1;
transform: none;
}
}
已编译的CSS:
.project {
opacity: 0;
}
.project.animated {
opacity: 1;
animation-name: fadeInDown;
animation-duration: 1s;
}
.project.animated:nth-child(2) {
animation-delay: .3s;
}
.project.animated:nth-child(3) {
animation-delay: .6s;
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translate3d(0, -40%, 0);
}
to {
opacity: 1;
transform: none;
}
}
答案 0 :(得分:3)
选项1:
从opacity: 1
课程中移除.animated
并添加animation-fill-mode: forwards
。此设置意味着动画元素将保持其最后一个关键帧(具有opacity: 1
)的状态,因此不需要额外的属性设置。
window.onload = function() {
setTimeout(function() {
var els = document.querySelectorAll('.project');
for (var i = 0; i < els.length; i++) {
els[i].classList.add('animated');
}
}, 100);
}
&#13;
.project {
opacity: 0;
}
.project.animated {
/*opacity: 1;*/
animation-name: fadeInDown;
animation-duration: 1s;
animation-fill-mode: forwards;
}
.project.animated:nth-child(2) {
animation-delay: .3s;
}
.project.animated:nth-child(3) {
animation-delay: .6s;
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translate3d(0, -40%, 0);
}
to {
opacity: 1;
transform: none;
}
}
/* just for demo */
.project {
height: 100px;
width: 100px;
background: red;
&#13;
<div class='project'>First</div>
<div class='project'>Second</div>
<div class='project'>Third</div>
&#13;
选项2:
如果由于某种原因您不想从opacity: 1
类中删除.animated
,请将animation-fill-mode: backwards
设置为该元素。这将使动画元素在opacity: 0
期间保持其第一个关键帧(animation-delay
)中提到的状态,因此该元素不会立即显示。
window.onload = function() {
setTimeout(function() {
var els = document.querySelectorAll('.project');
for (var i = 0; i < els.length; i++) {
els[i].classList.add('animated');
}
}, 100);
}
&#13;
.project {
opacity: 0;
}
.project.animated {
opacity: 1;
animation-name: fadeInDown;
animation-duration: 1s;
animation-fill-mode: backwards;
}
.project.animated:nth-child(2) {
animation-delay: .3s;
}
.project.animated:nth-child(3) {
animation-delay: .6s;
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translate3d(0, -40%, 0);
}
to {
opacity: 1;
transform: none;
}
}
/* just for demo */
.project {
height: 100px;
width: 100px;
background: red;
&#13;
<div class='project'>First</div>
<div class='project'>Second</div>
<div class='project'>Third</div>
&#13;
答案 1 :(得分:1)
.project.animated {
opacity: 1; <- REMOVE THIS
animation-name: fadeInDown;
animation-duration: 1s;
[...]
您不需要在课程中指定opacity: 1;
,@keyframes
动画会将每个<div>
设置为完全不透明的动画。