动画CSS延迟下划线

js1*_*111 0 css css3 css-animations

我正在尝试动画(从左到右)带有页面加载转换延迟的下划线.我知道如何让它在悬停时工作,但不是在加载时.尝试这样的东西,但不知道为什么它不会工作.

.under {
    position: relative;
    text-decoration: none;
    display: inline-block;
}
.under::after {
    content: "";
    position: absolute;
    width: 100%;
    height: 2px;
    bottom: 0;
    left: 0;
    background-color: #000;
    -webkit-transition-delay: 2s; 
    transition-delay: 2s;
    -webkit-transition: all 0.3s ease-in-out 0s;
    transition: all 0.3s ease-in-out 0s;
}
Run Code Online (Sandbox Code Playgroud)

Har*_*rry 5

在尝试达到您正在寻找的效果时,有两点需要注意:

  • text-decoration 属性不能动画,以使下划线从左到右.
  • CSS 只有在状态发生变化时transition才会触发(由于用户交互,例如悬停,点击等,或者由于像setTimeout这样的JavaScript).如果你需要在页面加载时发生动画,那么你应该使用CSS animation和@keyframes规则.

作为旁注,在您的代码中,transition-delay在transition属性之前添加,而short-hand属性的延迟值为0s.由于这在CSS中稍后出现,它将覆盖transition-delay: 2s之前指定的.


如何实现这种效果?

这是一个你想要实现的相当简单的效果,因此不需要SVG.如果下划线弯曲(或)像弧形,我会建议使用SVG.

使用伪元素:

在下面的代码片段中,我使用了一个伪元素并将其定位,使其生成一条看起来像文本下划线的线条.通过将伪元素设置width为0-100%的动画,可以实现所需的效果.所述height伪元件的确定的边界的厚度和background-color确定边框的颜色.

.underline {
  display: inline-block;
  position: relative;
  padding-bottom: 4px;
  margin-bottom: 10px;
}
.underline:after {
  position: absolute;
  content: '';
  bottom: -2px;
  left: 0px;
  height: 2px;
  width: 0%;
  background-color: red;
  animation: underline 2s ease-in-out 2s infinite; /* remove infinite if you want only once */
}
@keyframes underline {
  to {
    width: 100%;
  }
}
Run Code Online (Sandbox Code Playgroud)
<div class='underline'>Some underlined text</div>
<br>
<div class='underline'>Some lengthy underlined text</div>
Run Code Online (Sandbox Code Playgroud)


使用线性渐变:

通过使用linear-gradient图像作为元素的背景也可以实现相同的目的.这里background-sizeX轴的动画范围为0% - 100%.的background-size在Y轴确定的边界的厚度和linear-gradient确定边框的颜色.

.underline {
  display: inline-block;
  position: relative;
  padding-bottom: 4px;
  margin-bottom: 10px;
  background: linear-gradient(to right, red, red);
  background-size: 0% 2px;
  background-repeat: no-repeat;
  background-position: left bottom;
  animation: underline 2s ease-in-out 2s infinite; /* remove infinite if you want only once */
}
@keyframes underline {
  to {
    background-size: 100% 2px;
  }
}
Run Code Online (Sandbox Code Playgroud)
<div class='underline'>Some underlined text</div>
<br>
<div class='underline'>Some lengthy underlined text</div>
Run Code Online (Sandbox Code Playgroud)