首页 > 解决方案 > 如何使用 CSS 动画在其上方的文本块后 2 秒内使文本滑动

问题描述

我正在尝试使用 HTML 和 CSS 动画让一些文本从左侧滑到网页的中心。目标是让第一个文本块首先滑入中心,然后在 2 秒延迟后,让第二个文本块滑入中心。这样读者在页面上看到的线条就会产生很好的效果。

这是HTML代码:

/* .slide1 {
  -webkit-animation : slideIn 2s forwards;
  -moz-animation    : slideIn 2s forwards;
  animation         : slideIn 2s forwards;
  } */
.slide2 {
  /* animation-delay: 2s; */
  margin-top        : -20px;
  -webkit-animation : slideIn 2s forwards;
  -moz-animation    : slideIn 2s forwards;
  animation         : slideIn 2s forwards;
} 
@-webkit-keyframes slideIn {
  0%   { transform: translateX(-900px); }
  100% { transform: translateX(0);      }
}
@-moz-keyframes slideIn {
  0%   { transform: translateX(-900px); }
  100% { transform: translateX(0);      }
}
@keyframes slideIn {
  0%   { transform: translateX(-900px); }
  100% { transform: translateX(0);      }
}
<h1 class="slide1">You want to go to the moon.<br></h1>
<h1 class="slide2">We’re here to give you a shot.</h1>

所以问题是,当您取消注释上面的类 slide1 时,动画适用于第二行,但不适用于第一行。
整个事情一起移动,这不是应该发生的事情。在幻灯片 2 中延迟动画的意义在于,在第一个文本块移动到中心之后,第二个文本块将开始向右移动。
令人困惑的是为什么这不起作用-

标签: htmlcssanimation

解决方案


您必须首先将您的.slide1.slide2屏幕外的

transform : translateX(-100vw);

...与您的想象相反,css 命令还必须遵守命令,并且您的delay命令必须放在您的全局命令之后translate

非常非常糟糕

animation-delay : 2s;
animation       : 2s slideIn forwards; 

(它使animation-delay : 0;

animation       : 2s slideIn forwards;
animation-delay : 2s;

. 否则你必须尊重参数的正确顺序

animation : 2s 2s slideIn forwards;

但在我看来,最好的写法是——无需重复 css:

.slide {
  text-align : center;
  transform  : translateX(-100vw);
  animation  : 2s slideIn forwards;
  }  
.second {
  margin-top      : -.8em;
  animation-delay : 2s;
  } 
@keyframes slideIn {
  0%   { transform : translateX(-100vw); }
  100% { transform : translateX(0);      }
  }
<h1 class="slide">You want to go to the moon.</h1>
<h1 class="slide second">We’re here to give you a shot.</h1>

还要注意单位的使用,以及无论显示宽度如何,使文本居中的正确方法(正如您在问题中指出的那样)


推荐阅读