我有一些词,例如“美丽”、“棒极了”、“不错”和“精彩”。
我想在无限时间内将每个单词显示为一个接一个地键入文本效果。
看我想要这样:google forms
我制作了运行的文字效果。 看下面的代码:
var myText= "beautiful";
var text = myText.split("");
var counter = 0;
function typeIt(text){
var SI=setInterval(function(){
var h1 = $("#myTypingText");
h1.append(text[counter]);
counter++;
if(counter==text.length){
clearInterval(SI);
}
},70);
}
我无法无限期地为每个单词一个接一个地运行此函数。
请帮我解决这个问题。
提前致谢。
最佳答案
您可以修改现有函数以接受单词数组,并逐个处理单词。
编辑:展开第一个片段以查看我的原始答案,该答案在单词之间没有延迟:
function typeIt(words) {
var letterIndex = 0;
var wordIndex= 0;
var h1 = $("#myTypingText");
var SI = setInterval(function() {
if (letterIndex === words[wordIndex].length) { // if at end of current word
wordIndex = (wordIndex + 1) % words.length; // go to next word
letterIndex = 0;
h1.empty(); // clear output div
}
h1.append(words[wordIndex][letterIndex]);
letterIndex++;
}, 70);
}
typeIt(["beautiful", "awesome", "nice", "wonderful"]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myTypingText"></div>
请注意,您不需要.split("")
这个词,因为您可以使用与引用数组元素相同的方括号语法直接引用字符串中的各个字符,例如,"text"[2]
是 "x"
。
您可以使用 setTimeout()
来控制单词之间的延迟:
function typeIt(words) {
var letterIndex = 0;
var wordIndex = 0;
var h1 = $("#myTypingText");
(function nextWord() {
var SI = setInterval(function() {
h1.append(words[wordIndex][letterIndex]);
letterIndex++;
if (letterIndex === words[wordIndex].length) {
wordIndex = (wordIndex + 1) % words.length;
letterIndex = 0;
clearInterval(SI);
setTimeout(function() {
h1.empty();
nextWord();
}, 1000); // delay between words
}
}, 70); // delay between letters
})();
}
typeIt(["beautiful", "awesome", "nice", "wonderful"]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myTypingText"></div>
请注意,这不一定是构建代码的最简洁的方式,但它似乎是修改已有内容以实现所需输出的最快方式。
关于javascript - 运行文字效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39301783/