我正在尝试制作一个 jQuery 函数来逐个字母地拼出我的名字。我的名字是 jack ,所以我希望它一开始什么都没有,然后它会显示一个 J,然后是 Ja,然后是 Jak,然后是 Jake。假设我正在修改具有类名的段落元素:
<p class=Name> *name gets 'typed' here* </p>
我试过使用 .delay() 函数和 setTimeout() 函数,但我是 jQuery 的新手,所以我可能用错了它们。
$(document).ready(function()
{
setTimeout(function(){$(".name").text('J');}, 500);
setTimeout(function(){$(".name").text('Ja');}, 500);
setTimeout(function(){$(".name").text('Jak');}, 500);
setTimeout(function(){$(".name").text('Jake');}, 500);
});
这是我最近尝试的一个 fiddle :
这只是延迟 500 毫秒,然后一次输入我的名字。我试图让它每 500 毫秒输入一个字母。有人可以帮我弄清楚如何做到这一点吗?
最佳答案
只需使用 recursive function :
var name = "Jake";
function typeName(name, iteration) {
// Prevent our code executing if there are no letters left
if (iteration === name.length)
return;
setTimeout(function() {
// Set the name to the current text + the next character
// whilst incrementing the iteration variable
$('.name').text( $('.name').text() + name[iteration++] );
// Re-trigger our function
typeName(name, iteration);
}, 500);
}
// Call the function to begin the typing process
typeName(name, 0);
我们可以稍微扩展它以消除最初传递 iteration
变量的需要,方法是将其添加为我们的 typeName
函数的第一行:
var iteration = iteration || 0;
现在你可以简单地调用:
typeName("My name here");
关于javascript - 您将如何使用 jQuery 创建 "typing"效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24514173/