jQuery函数一次显示一个字符的文本 [英] jquery function to display text one character at a time
本文介绍了jQuery函数一次显示一个字符的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何人都可以帮助这个Jquery吗?我正在尝试创建一个函数,该函数接受文本的可变部分,然后稍微延迟地输出每个字母.这是我的代码
Can anyone help with this Jquery ? I am trying to create a function that accepts a variabe of text and then outputs each letter with a slight delay. here is the code i have
//example of function call
var data = "hi you there";
display_text(data);
//function to fade words in individually
function display_text(data) {
var $words = data.split(" ");
var html = "";
for (var i = 0; i < words.length; i++) {
html += "<span>" + words[i] + " </span>";
};
html.insertBefore("#placeholder").hide().each(function(i){
$(this).delay(i*100).fadeIn(700);
}
);
推荐答案
除了使用jquery的.delay之外,您还可以使用javascript的setTimeout来实现相同的目的.为了使其更通用,您还可以接受要在其中显示文本并作为参数延迟的元素.
Instead of using .delay of jquery you can also use javascript's setTimeout to achieve the same thing. To make it a more generalized variant you can also accept the element where the text to be shown and delay as arguments.
这是代码.
HTML
<body>
<div id="myText"></div>
</body>
JS
var text="This text will be written one by one.";
var delay=300;
var elem = $("#myText");
//text- string
//elem - jQuery element where text is to be attached
//delay - the delay in each text
var addTextByDelay = function(text,elem,delay){
if(!elem){
elem = $("body");
}
if(!delay){
delay = 300;
}
if(text.length >0){
//append first character
elem.append(text[0]);
setTimeout(
function(){
//Slice text by 1 character and call function again
addTextByDelay(text.slice(1),elem,delay);
},delay
);
}
}
addTextByDelay(text,elem,delay);
我还创建了一个小提琴输入带有延迟的文本
I have also created a fiddle Enter Text with Delay
这篇关于jQuery函数一次显示一个字符的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文