我正在尝试创建一个 jQuery 函数来逐个字母地拼出我的名字。我的名字是 Jake,所以我希望它一开始什么都没有,然后它会显示一个 J,然后是 Ja,然后是 Jak,然后是 Jake。假设我正在修改带有类名的段落元素:
<p class=Name> *name gets 'typed' here* </p>
Run Code Online (Sandbox Code Playgroud)
我尝试过使用 .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);
});
Run Code Online (Sandbox Code Playgroud)
这是我最近尝试的一个jfiddle:
这只会延迟 500 毫秒,然后一次性输入我的名字。我试图让它每 500 毫秒输入一个字母。有人可以帮我弄清楚如何做到这一点吗?
只需使用递归函数:
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);
Run Code Online (Sandbox Code Playgroud)
iteration我们可以稍微扩展它,通过将其添加为函数中的第一行来消除最初传递变量的需要typeName:
var iteration = iteration || 0;
Run Code Online (Sandbox Code Playgroud)
现在您只需调用:
typeName("My name here");
Run Code Online (Sandbox Code Playgroud)