首页 > 解决方案 > 打字文字动画无法控制宽度

问题描述

所以基本上我有这个打字文本动画,其中一些 javascript 每 3 秒更改一条消息,并且在我的 jquery 代码更改消息之前使用 css 关键帧“重新键入”文本。目前它工作正常,但宽度是静态的,所以对于较小的世界,宽度仍然设置为 7ch,最终看起来很傻。我尝试了一些不同的解决方法,例如将宽度设置为自动,将 div 设置为然后将宽度设置为继承,但是所有想法都失败了。

@keyframes terminal {
  0% {width:0}
  20% {width:0}
  50% {width:7ch}
  70% {width:7ch}
  100% {width:0}
}
#terminal-text {
  font-weight: bold;
  margin: 1em 0 .5em 0;
  padding: 0;
  animation: terminal 3s infinite;
  overflow: hidden;
  white-space: nowrap;
  border-right: 4px solid black;
  text-align: left;
}
<center style="display: flex;">
    <h1 style="padding-right:20px;">We</h1>
    <h1 id="terminal-text">innovate.</h1>
</center>
<script type="text/javascript">
    var i = 0;
    words = ['architect.','build.','design.','code.','develop.','innovate.'];
    setInterval(function() {
      $("#terminal-text").text(words[i]);
      i++;
      if (i > words.length) {
        i=0;
      }
    },3000);
</script>

标签: jquerycss

解决方案


而不是动画width,动画max-width

var i = 0;
words = ['architect.','build.','design.','code.','develop.','innovate.'];
setInterval(function() {
  $("#terminal-text").text(words[i]);
  i++;
  if (i > words.length) {
    i=0;
  }
},3000);
@keyframes terminal {
  0% {max-width:0}
  20% {max-width:0}
  50% {max-width:100%}
  70% {max-width:100%}
  100% {max-width:0}
}
#terminal-text {
  font-weight: bold;
  margin: 1em 0 .5em 0;
  padding: 0;
  animation: terminal 3s infinite;
  overflow: hidden;
  white-space: nowrap;
  border-right: 4px solid black;
  text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<center style="display: flex;">
    <h1 style="padding-right:20px;">We</h1>
    <h1 id="terminal-text">innovate.</h1>
</center>


推荐阅读