【问题标题】:Typewriter animation plugin bug打字机动画插件错误
【发布时间】:2020-05-22 10:53:01
【问题描述】:

我遇到了这个 CodePen - https://codepen.io/Danielgroen/pen/VeRPOq。它被广泛用作打字机动画的示例,但一旦您开始编辑它就会显示错误。 CodePen 说“未捕获的 TypeError:无法读取未定义的属性 'length'”,JS 选项卡中的第 19 行。任何想法为什么会发生这种情况?

提前感谢您!

enter image description here

document.addEventListener('DOMContentLoaded',function(event){
  // array with texts to type in typewriter
  var dataText = [ "Amsterdam.", "Full Service.", "Webdevelopment.", "Wij zijn Occhio!"];
  
  // type one text in the typwriter
  // keeps calling itself until the text is finished
  function typeWriter(text, i, fnCallback) {
    // chekc if text isn't finished yet
    if (i < (text.length)) {
      // add next character to h1
     document.querySelector("h1").innerHTML = text.substring(0, i+1) +'<span aria-hidden="true"></span>';

      // wait for a while and call this function again for next character
      setTimeout(function() {
        typeWriter(text, i + 1, fnCallback)
      }, 100);
    }
    // text finished, call callback if there is a callback function
    else if (typeof fnCallback == 'function') {
      // call callback after timeout
      setTimeout(fnCallback, 700);
    }
  }
  // start a typewriter animation for a text in the dataText array
   function StartTextAnimation(i) {
     if (typeof dataText[i] == 'undefined'){
        setTimeout(function() {
          StartTextAnimation(0);
        }, 20000);
     }
     // check if dataText[i] exists
    if (i < dataText[i].length) {
      // text exists! start typewriter animation
     typeWriter(dataText[i], 0, function(){
       // after callback (and whole text has been animated), start next text
       StartTextAnimation(i + 1);
     });
    }
  }
  // start the text animation
  StartTextAnimation(0);
});
body {
  background-color: #FF5A5A;
  height: 100%;
  font-family: 'tradegothiclt-bold', sans-serif;
}

h1 {
  font-size: 5em;
  color: white;
  text-transform: uppercase;
}

span {
  border-right: .05em solid;
  animation: caret 1s steps(1) infinite;
}

@keyframes caret {
  50% {
    border-color: transparent;
  }
}
  &lt;h1&gt;Hallo, Wij zijn Occhio!&lt;/h1&gt;

【问题讨论】:

  • 我认为实际的错误来自 if (i &lt; dataText[i].length) { ,而应该是 if (i &lt; dataText.length) {
  • 天啊!你是绝对正确的!排序!!!非常感谢!

标签: javascript codepen


【解决方案1】:

实际错误来自if (i &lt; dataText[i].length) { 行, 来自函数StartTextAnimation作者正在检查索引是否仍然小于给定的单词列表长度 动画

因此将其更改为 if (i &lt; dataText.length) { 应该可以正常工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 2021-01-22
    • 2022-10-20
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多