我是一个用JavaScript创建打字效果的脚本。我试图循环它,以便它在执行结束10秒后在循环中执行。换句话说,存在打字效果,并且当在十秒钟之后写入文本时将再次执行。我尝试过使用setTimeout()
,但它没有用。
提前感谢您的帮助。
function setupTypewriter(t) {
var HTML = t.innerHTML;
t.innerHTML = "";
var cursorPosition = 0,
tag = "",
writingTag = false,
tagOpen = false,
typeSpeed = 50,
tempTypeSpeed = 0;
var type = function() {
if (writingTag === true) {
tag += HTML[cursorPosition];
}
if (HTML[cursorPosition] === "<") {
tempTypeSpeed = 0;
if (tagOpen) {
tagOpen = false;
writingTag = true;
} else {
tag = "";
tagOpen = true;
writingTag = true;
tag += HTML[cursorPosition];
}
}
if (!writingTag && tagOpen) {
tag.innerHTML += HTML[cursorPosition];
}
if (!writingTag && !tagOpen) {
if (HTML[cursorPosition] === " ") {
tempTypeSpeed = 0;
}
else {
tempTypeSpeed = (Math.random() * typeSpeed) + 50;
}
t.innerHTML += HTML[cursorPosition];
}
if (writingTag === true && HTML[cursorPosition] === ">") {
tempTypeSpeed = (Math.random() * typeSpeed) + 50;
writingTag = false;
if (tagOpen) {
var newSpan = document.createElement("span");
t.appendChild(newSpan);
newSpan.innerHTML = tag;
tag = newSpan.firstChild;
}
}
cursorPosition += 1;
if (cursorPosition < HTML.length - 1) {
setTimeout(type, tempTypeSpeed);
}
};
return {
type: type
};
}
var typer = document.getElementById('typewriter');
typewriter = setupTypewriter(typewriter);
typewriter.type();
答案 0 :(得分:1)
typewriter = setupTypewriter(typewriter);
您将typewriter
变量传递给setupTypewriter
,但它尚不存在。在这里你要使用
typewriter = setupTypewriter(typer);
顺便说一句,我无法理解你如何打印标签。您以零延迟打印<
,d
,i
,v
,>
,但解析器仍然可能会中断。您应该立即打印标签:<div></div>
然后将div的内容附加到它。
答案 1 :(得分:0)
你想要setInterval。
setInterval(function(){alert(&#34; Hello&#34;);},3000);
此代码每三秒运行一次。
此处提供完整的文档,示例等(包括如何阻止它):