【问题标题】:How do I loop through array elements infinitely, whilst making the current array element visible?如何无限循环遍历数组元素,同时使当前数组元素可见?
【发布时间】: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;


【问题讨论】:

标签: javascript html css arrays for-loop


【解决方案1】:

首先,在“onTick' 函数,您正在尝试访问 '当前词' 变量,但未在该范围内定义。此外,完整的功能似乎并没有调用 '动画词' 更新标题中文本的函数。

以下是如何使用计时器为文本设置动画的示例:

const arrayOfWords = ["Acerbity", "Anomalous", "Asymetrical", "Analytical", "Arbritrary"];
const targetDisplay = document.querySelector("h1#heading");
let currentWord = 0;

function animateWords(){
targetDisplay.innerText = arrayOfWords[currentWord];

if(currentWord < arrayOfWords.length-1) {
  currentWord++;
}
else{
  currentWord=0;
 }
}

const timer = setInterval(animateWords, 1000); // 1000ms = 1 second

在这个例子中,设置间隔函数用于调用动画词每 1000 毫秒(1 秒)运行一次。这动画词函数更新标题中的文本并递增当前词多变的。当 currentWord 到达数组末尾时,它被重置为 0 以再次开始动画。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多