【发布时间】:2021-01-23 12:49:47
【问题描述】:
当到达最后一个数组时,我正试图停止擦除我的“自动键入的文本”。 我一直在谷歌上搜索,但找不到任何解决方案。
const typedTextSpan = document.querySelector(".typed-text");
const cursorSpan = document.querySelector(".cursor");
const textArray = ["reconnaitre un talent ?", "détécter une opportunité ?"];
const typingDelay = 170;
const erasingDelay = 100;
const newTextDelay = 2000;
let textArrayIndex = 0;
let charIndex = 0;
function type() {
if (charIndex < textArray[textArrayIndex].length) {
if (cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing");
typedTextSpan.textContent += textArray[textArrayIndex].charAt(charIndex);
charIndex++;
setTimeout(type, typingDelay);
} else {
cursorSpan.classList.remove("typing");
setTimeout(erase, newTextDelay);
}
}
function erase() {
if (charIndex > 0) {
if (!cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing");
typedTextSpan.textContent = textArray[textArrayIndex].substring(0, charIndex - 1);
charIndex--;
setTimeout(erase, erasingDelay);
} else {
cursorSpan.classList.remove("typing");
textArrayIndex++;
if (textArrayIndex >= textArray.length) textArrayIndex = 0;
setTimeout(type, typingDelay + 1100);
}
}
document.addEventListener("DOMContentLoaded", function() {
if (textArray.length) setTimeout(type, newTextDelay + 250);
});
<div class="container" id="container">
<h1>Savez-vous <span class="typed-text" id="typed-text"></span><span class="cursor" id="cursor"> </span></h1>
</div>
【问题讨论】:
标签: javascript arrays erase