我有一个文本元素(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秒钟后,我无法再次播放动画。有人可以帮我吗?谢谢。
答案 0 :(得分:2)
首先,您正在使用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秒更改一次文本,此代码将为您提供帮助。
您可以添加任意数量的文本。
答案 1 :(得分:0)
我找到了一个使用JavaScript的解决方案,可以将元素的宽度从1%增加到100%! 这是我的JavaScript代码:
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;
var width = 0;
var id = setInterval(frame,10);
function frame(){
if(width >= 100){
clearInterval(id);
} else {
width++;
themes.style.width = width + "%";
}
}
//Change the counter variable
curr += 1;
//Change the counter to the start of the array
if(curr >= texts.length) curr = 0;
}, 4000);
谢谢您的帮助!