【发布时间】:2023-01-13 02:54:45
【问题描述】:
我希望创建一个文本动画,其中以适中的速度一个接一个地显示单词。首先,我尝试通过 onClick 事件实现这一点。
const arrayOfWords = ["Acerbity", "Anomalous", "Asymetrical", "Analytical", "Arbritrary"];
const targetOfDisplay = document.querySelector("h1#heading");
const clickElement = document.querySelector("button");
targetOfDisplay.innerHTML = arrayOfWords[0];
let i = 0;
function changeWord(){
if(i < arrayOfWords.length-1) {
i++;
}
else{
i=0;
}
return targetOfDisplay.innerText = arrayOfWords[i];
}
clickElement.onclick = changeWord;
然后我想到用它制作动画。
我尝试使用计时器,但我无法弄清楚。
const arrayOfWords = ["Acerbity", "Anomalous", "Asymetrical", "Analytical", "Arbritrary"];
const targetDisplay = document.querySelector("h1#heading");
let i = 0;
targetDisplay.innerHTML = arrayOfWords[0];
function animateWords(){
if(i < arrayOfWords.length-1) {
i++;
}
else{
i=0;
}
return targetDisplay.innerText = arrayOfWords[i];
}
const currentWord = 0;
const timer = setInterval(onTick,50);
function onTick(){
const change = targetOfDisplay.innerText[currentWord];
currentWord++
if(current === arrayOfWords.length){
complete();
return;
}
}
function complete(){
clearInterval(timer);
timer = null;
【问题讨论】:
-
你永远不会打电话给
animateWords()。也许你想要const timer = setInterval(animateWords, 50);。
标签: javascript html css arrays for-loop