gpt4 book ai didi

Javascript 和 css 动画总是不同步

转载 作者:太空宇宙 更新时间:2023-11-04 00:40:01 25 4
gpt4 key购买 nike

所以基本上我的 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 和 css 动画总是不同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58510777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com