CSS 打字机效果

标签 css animation

我正在尝试创建一个打字机效果,其中文本被写出,然后在句子的末尾 |光标闪烁 2 秒,然后开始下一个句子(第二个 h1),然后写下那个句子。

body {
  background: #333;
  padding-top: 5em;
  display: flex;
  justify-content: center;
}

.typewriter h1 {
  color: #fff;
  font-family: monospace;
  overflow: hidden;
  border-right: .15em solid orange;
  white-space: nowrap;
  margin: 0 auto;
  letter-spacing: .15em;
  animation: typing 3.5s steps(30, end), blink-caret .5s;
}

@keyframes typing {
  from {
    width: 0
  }
  to {
    width: 100%
  }
}

@keyframes blink-caret {
  from,
  to {
    border-color: transparent
  }
  50% {
    border-color: orange
  }
}
<div class="typewriter">
  <h1>First Sentence Here</h1>
  <h1>Second Sentence Here</h1>
</div>

最佳答案

您可以使用 CSS 变量添加 animation-delay。对于每个 h1 元素(接受第一个 - 它使用默认值),设置 --delay 变量。这将为每个动画添加相关延迟。

您还应该将 animation-fill-mode 更改为 both,这样元素将保留其开始和结束状态。

body {
  background: #333;
  padding-top: 5em;
  display: flex;
  justify-content: center;
}

.typewriter h1 {
  color: #fff;
  font-family: monospace;
  overflow: hidden;
  border-right: .15em solid orange;
  white-space: nowrap;
  margin: 0 auto;
  letter-spacing: .15em;
  animation: typing 3.5s steps(30, end) both, blink-caret .5s both;
  animation-delay: calc(var(--delay, 0) * 1s), calc(var(--delay, 0) * 1s + 3.5s);
}

@keyframes typing {
  from {
    width: 0
  }
  to {
    width: 100%
  }
}

@keyframes blink-caret {
  from,
  to {
    border-color: transparent
  }
  50% {
    border-color: orange
  }
}
<div class="typewriter">
  <h1>First Sentence Here</h1>

  <h1 style="--delay: 4">Second Sentence Here</h1>
</div>

关于CSS 打字机效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58666212/

相关文章:

html 类别/子类别最佳 View

javascript - 如何使用sttrek/scrollMonitor的方法 'one'?

jquery - 链接影响不同元素的 jQuery 动画

css - 在动画之后转换属性

Python FuncAnimation 只节省了 30%

javascript - 从头开始恢复动画 css3

css - 使用 CSS 匹配空输入框

php - home.body 上的 jquery 图像随机

javascript - 自动制作所有图像 Bootstrap 响应类

css - 嵌套 div 背景色