因此,基本上我的CSS动画应该模拟一些正在键入,未键入并最终更改为另一个单词的文本。通常,CSS关键帧和JavaScript setInterval是同步的,但是在移动设备上,它们有时会不同步,或者如果我转到新标签页,它们将失去同步。

<center style="display: flex; width:70vw">
     <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>


#header .banner h1 {
  margin: 1em 0 .5em -10%;
  padding: 0;
  color: white;
  text-align: left;
}
@keyframes terminal {
  0% {max-width:0}
  50% {max-width:100%}
  55% {max-width:100%}
  100% {max-width:0}
}
#header #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 white;
  text-align: left;
}

最佳答案

而不是在JavaScript中使用setInterval(),您可以侦听动画结束事件。您的方法的问题在于您不能同时启动两个“计时器”(css / js)(可以使用另一种方法),但这可以解决您的问题



var wordIndex = 0;
words = ['architect.','build.','design.','code.','develop.','innovate.'];

var changeWord = function() {
  $("#terminal-text").text(words[wordIndex++]);
};

var element = document.querySelector("#terminal-text");
element.addEventListener("animationiteration", changeWord, false);

// you could also do something special on start event
// replace changeWord with whatever functionality you need
// element.addEventListener("animationstart", changeWord, false);

// animationend will never be triggered in your code at the moment
// but maybe you want to do something with it somewhen
// element.addEventListener("animationend", function() {console.log('animation ended')}, false);

#header .banner h1 {
  margin: 1em 0 .5em -10%;
  padding: 0;
  color: white;
  text-align: left;
}
@keyframes terminal {
  0% {max-width:0}
  50% {max-width:100%}
  55% {max-width:100%}
  100% {max-width:0}
}
#header #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 white;
  text-align: left;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header">
  <center style="display: flex; width:70vw">
    <h1 style="padding-right:20px;">We</h1>
    <h1 id="terminal-text">innovate.</h1>
  </center>
</div>

关于javascript - Javascript和CSS动画不同步,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58510777/

10-12 12:40
查看更多