javascript - 更改元素内的文本后如何重复动画?

标签 javascript html css animation

我有一个文本元素(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/

相关文章:

html - 占位符加载卡无法正常工作

javascript - 在Javascript中的句子(多个句子)的第一个和最后一个单词中添加方括号

javascript - 谷歌应用脚​​本: Time Driven Triggers timezone issue

javascript - Postgres 和 NodeJs api 中的 404 Not found 错误(可能重复)

css - Foundation .large9 和列

html - 在网站中使用具有固定高度的空 div 是否正确?

html - 我想全屏显示图像,直到我滚动

javascript - Node.js 捕获并重试 ECONNRESET

JavaScript Canvas - 平滑改变 rgb

html - 为什么内容不会采用不同的背景颜色?