我有一个文本元素(HTML),它在页面加载时播放动画,我正在尝试创建一个脚本将原始文本更改为不同的文本,然后播放相同的动画。这是我的代码的一部分:
setTimeout(function typewriter() {
let txt;
let themes = document.getElementById("themes");
txt = "Games";
themes.innerText = txt;
themes.classList.add("changer");
}, 4000);
.typewriter h1 {
color: #ffffff;
background-color: #000000a8;
border-radius: 5px;
padding: 10px;
font-family: monospace;
font-size: 35px;
overflow: hidden; /* Ensures the content is not revealed until the animation */
border-right: .15em solid #333333; /* The typwriter cursor */
white-space: nowrap; /* Keeps the content on a single line */
margin: 0 auto; /* Gives that scrolling effect as the typing happens */
animation:
typing 2s steps(30, end),
blink-caret .5s step-end infinite;
}
.changer {
animation: typing 2 s steps(30, end),blink - caret .5 s step - end infinite;
}
/* The typing effect */
@keyframes typing {
from { width: 0 }
to { width: 100% }
}
/* The typewriter cursor effect */
@keyframes blink-caret {
from, to { border-color: transparent }
50% { border-color: #333333 }
}
<div class="typewriter">
<h1 id="themes">Science</h1>
</div>
问题是 4 秒后,当文本发生变化时,我无法再次播放动画。有人可以帮我吗?谢谢。
最佳答案
首先,您正在使用 setTimeout (这是错误的) 如果你想让它重复这个功能,你应该使用setInterval。
其次,每次调用该函数时都会更改相同的“文本”,即“游戏”。如果你想让它变成某个文本,你需要先将它存储在一个数组中,
var texts = [];
//Add a counter
var curr = 0;
//Store in array
texts.push("Games");
texts.push("Science");
setInterval(function() {
let txt;
//Change the texts array value with curr variable (the Counter)
txt = texts[curr];
let themes = document.getElementById("themes");
themes.innerText = txt;
themes.classList.add("changer");
//Change the counter variable
curr += 1;
//Change the counter to the start of the array
if(curr >= texts.length) curr = 0;
}, 4000);
就我而言,动画不起作用。但如果您想每 4 秒更改一次文本,此代码将对您有所帮助。
您可以添加任意数量的文本。
关于javascript - 更改元素内的文本后如何重复动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50966790/