css - 延迟时的动画 CSS 下划线

标签 css 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;
}

最佳答案

在尝试实现您正在寻找的效果时,需要注意两件事:

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

作为旁注,在您的代码中,transition-delay 被添加到 transition 属性之前,并且简写属性的延迟值为 0s 。由于它稍后出现在 CSS 中,因此它将覆盖之前指定的 transition-delay: 2s


如何实现这种效果?

这是您要实现的相当简单的效果,因此并不是真正需要 SVG。如果下划线是 flex 的(或)像弧线,我会建议使用 SVG。

使用伪元素:

在下面的代码片段中,我使用了一个伪元素并将其定位为生成一条看起来像文本下划线的行。通过在 0 - 100% 之间设置伪元素的 width 动画,可以实现所需的效果。伪元素的 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%;
  }
}
<div class='underline'>Some underlined text</div>
<br>
<div class='underline'>Some lengthy underlined text</div>


使用线性渐变:

同样可以通过使用linear-gradient 图像作为元素的背景来实现。这里的 X 轴中的 background-size 从 0% - 100% 动画。 Y 轴上的 background-size 决定边框粗细,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;
  }
}
<div class='underline'>Some underlined text</div>
<br>
<div class='underline'>Some lengthy underlined text</div>

关于css - 延迟时的动画 CSS 下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35641827/

相关文章:

javascript - 淡入淡出javascript

CSS 动画在 :hover animation 之后重新播放

javascript - 具有可滚动行和固定标题的表格

javascript - 是否可以在普通 Javascript 中同时运行多个 if 语句?如果是这样你怎么办?

html - 将 div 放在另一个旁边

css - 为一个元素使用多个动画

jquery - 使用 jQuery 和 CSS 转换的脉动效果

javascript - 当我使用 css 使其响应时,Html Canvas 变得模糊

具有关键帧和变换的 CSS3 动画

css - 在最后一帧停止 CSS3 动画