文字動畫error _ 換寫法


Posted by mijouhsieh on 2023-07-18

要解決的error.png

iconsArea.addEventListener("mouseover", (event) => {
  stopShow ()
  let target = event.target; 
  if (target.tagName !== "svg") {
    return;
  } else if (target.tagName === "svg") {
      stopShow();
  }

  let bouncingTexts = target.closest(".icons").children[3].children[0].innerHTML;
  let wrapText = ""
  for (let i = 0; i < bouncingTexts.length; i++) {
    wrapText += "<em class=''>" + bouncingTexts.charAt(i) + "</em>";
  }

  target.closest(".icons").children[3].children[0].innerHTML= wrapText;
  let letters = document.getElementsByTagName("em");
  let j = 0;

  function applyBounce( ) {
    if (letters[j] !== undefined && letters[j] !== null) {
      if(letters[j]) {
        setTimeout(function () {
          letters[j].classList.add('bounce-text')
          j++;
          if (j < letters.length) {
            applyBounce();
          }
        }, 250);
      }
    }
  }
  applyBounce( )
});

為什麼這行letters[j].classList.add('bounce-text') 會出現 Uncaught TypeError: Cannot read properties of undefined (reading 'classList')

這個錯誤通常發生在 letters[j] 為 undefined 或 null 時,而你試圖讀取它的 classList 屬性。這種情況可能發生在以下兩種情況下:

letters 陣列的長度小於 j + 1:這表示 letters 陣列中沒有 letters[j] 的索引位置。在迴圈中,j 的增加取決於 applyBounce() 函式的遞迴呼叫,直到 j 的值超過 letters 陣列的長度。因此,當 j 達到 letters.length 時,應該停止遞迴呼叫 applyBounce(),以避免出現這個錯誤。

letters[j] 元素不存在:這可能是因為在 letters 陣列中的某個索引位置上,沒有對應的 DOM 元素。這可能是由於 letters 陣列包含了其他非 標籤的元素,或者因為 letters 陣列是在 mouseover 事件處理程序中定義的,但事件處理程序被多次觸發,導致 letters 陣列中的元素不再存在。

為了解決這個問題,你可以嘗試進行以下更改:

在呼叫 applyBounce() 函式之前,添加一個條件檢查,確保 letters.length 大於 j。這可以避免在索引位置超出陣列長度時繼續執行遞迴呼叫。

function applyBounce() {
  if (j < letters.length) {
    你的程式碼
  }
}
``

在建立 letters 陣列之前,添加一個篩選器,僅選擇 標籤作為陣列元素。這樣可以確保 letters 陣列中的元素是有效的。

let letters = Array.from(document.getElementsByTagName("em"));
這些更改將確保在應用動畫效果之前,檢查 letters[j] 是否有效,從而避免出現該錯誤。


#文字動畫 #bouncing text







Related Posts

Why the HRCI PHRca Exam Matters for California HR Professionals?

Why the HRCI PHRca Exam Matters for California HR Professionals?

Web Component 實戰

Web Component 實戰

MTR04_1120

MTR04_1120


Comments