我正在尝试使用 jquery 模拟名称的输入,这是迄今为止我所拥有的:
var name = "hello there!";
var namesplit = name.split('');
$(document).ready(function () {
for (var i = 0; i < namesplit.length; i++) {
$('.wrapper h1').append(namesplit[i]);
}
});
基本上,我想要的是“你好!”中的每个 Angular 色。输入时,会有轻微的延迟,然后是下一个字符。另外,这是插入到其中有跨度(包含字符“|”)的 h1 中。我怎样才能防止它覆盖跨度(即它应该是这样的:你好!|不是|你好!)。谢谢!
最佳答案
在h1
中添加另一个跨度
<div class="wrapper">
<h1><span></span><span>|</span></h1>
</div>
然后
$(document).ready(function () {
var name = "hello there!";
var namesplit = name.split('');
$.each(namesplit, function (i, v) {
setTimeout(function () {
$('.wrapper h1 span:first').append(namesplit[i]);
}, i * 100)
})
});
演示:Fiddle
<小时/>如果您正在使用一个非常大的字符串,那么创建这么多次并不是一个好主意,然后尝试
$(document).ready(function () {
var name = "hello there!";
var namesplit = name.split('');
function print() {
if (!namesplit.length) {
return;
}
$('.wrapper h1 span:first').append(namesplit.shift());
setTimeout(print, 100)
}
print()
});
演示:Fiddle
关于javascript - 为数组中的每个项目添加延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21296981/