Javascript 中的文本动画无法正常工作

Text animation in Javascript not working properly

提问人:vinicioscst 提问时间:11/16/2023 更新时间:11/16/2023 访问量:27

问:

我想通过逐个字符添加其他文本来制作循环动画,以相同的方式删除它们并在开始循环之前更改文本。但是,正如您在这张 GIF 中看到的那样,一切都出错了。

这是我的代码现在的样子:

[HTML全
<h1 id="title">Desenvolvedor </h1>

JS公司

const title = document.getElementById("title");
const stacks = ["Front-End", "Back-End", "Full Stack"];
const speed = 200;
let stackIndex = 0;
let i = 0;

function addChar() {
  setTimeout(() => {
    title.innerHTML += stacks[stackIndex].charAt(i);
    i++;
    typeWriter(stackIndex);
  }, speed);
}

function deleteChar() {
  setTimeout(() => {
    title.innerHTML = title.innerHTML.slice(0, -1);
    
    if (title.innerText.length > 13) {
      deleteChar();
    } else {
      if (stackIndex > 1) {
        i = 0;
        stackIndex = 0;
        typeWriter(stackIndex);
      }

      i = 0;
      typeWriter(stackIndex++);
    }

  }, speed);
}

function typeWriter(stackIndex) {
  if (i < stacks[stackIndex].length) {
    addChar();
  } else {
    deleteChar();
  }
}

添加文本并更改其值按预期工作,但是当涉及到重置 stackIndexi 中的值并再次启动动画时,它开始出现错误,即使理论上它是从头开始重复整个代码。
如何修复此错误?有没有更实用的方法来制作这个动画?

JavaScript 动画

评论


答:

0赞 Isha Padalia 11/16/2023 #1

这是代码。希望它对你有用!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Animation</title>
</head>
<body>
    <h1 id="title">Desenvolvedor </h1>

    <script>
        const title = document.getElementById("title");
        const stacks = ["Front-End", "Back-End", "Full Stack"];
        const speed = 200;

        async function animateText() {
            for (let stackIndex = 0; stackIndex < stacks.length; stackIndex++) {
                await typeWriter(stackIndex);
                await sleep(1000); // Add a delay between texts
                await deleteText();
            }
            animateText(); // Loop the animation
        }

        async function typeWriter(stackIndex) {
            for (let i = 0; i < stacks[stackIndex].length; i++) {
                await sleep(speed);
                title.innerHTML += stacks[stackIndex].charAt(i);
            }
        }

        async function deleteText() {
            while (title.innerText.length > 13) {
                await sleep(speed);
                title.innerHTML = title.innerHTML.slice(0, -1);
            }
        }

        function sleep(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }

        animateText(); // Start the animation
    </script>
</body>
</html>