你可以做这样的事情。写出所有文本后,将welcome 的整个html 替换为原始文本。我承认这不是最好的。
http://jsfiddle.net/yN3xf/13/
$(document).ready(function() {
var htmlcopied = $('.welcome').html();
var textcopied = $('.welcome').text();
$('.welcome').text('');
function foobar(i) {
if (i < textcopied.length) {
$('.welcome').append(textcopied.charAt(i));
setTimeout(function() {
foobar(i + 1);
}, 80);
}
else {
$('.welcome').html(htmlcopied);
}
}
foobar(0);
});
更新
这应该通过不同的方式为您提供所需的效果。它在原始文本之上有一个 div,它缓慢地显示文本,看起来像是在输入。
示例
http://jsfiddle.net/guanome/LrbVy/
html
<div class="welcome">Hi, there <span class="hl">special text</span>, normal text
<div class="overlay"></div>
</div>
javascript
$(document).ready(function() {
$('.overlay').css('width', $('div.welcome').css('width'));
$('.overlay').css('height', $('div.welcome').css('height') + 15);
var origWidth = $('.overlay').css('width').replace(/px/g,'');
foobar(origWidth);
});
function foobar(i) {
if (i > -10) {
$('.overlay').css('width', i);
setTimeout(function() {
foobar(i - 10);
}, 80);
}
}
css
.hl{
color: red; font-family: helvetica;
background: #efefef;
color: black;
padding: 2px 7px;
-moz-box-shadow: 0 1px 1px #CCCCCC;
-webkit-box-shadow: 0 1px 1px #CCCCCC;
box-shadow: 0 1px 1px #CCCCCC;
}
div.welcome
{
position: relative;
width: 500px;
}
.overlay
{
position: absolute;
right: 0;
top: -3px;
width: 100%;
height: 25px;
background-color: #FFF;
z-index: 10;
}
更新 2
通过此更改,覆盖将动态添加到欢迎消息中,无需设置宽度,并且可以轻松处理多行。
http://jsfiddle.net/guanome/LrbVy/4/
html
<div class="welcome">Hi, there <span class="hl">special text</span>, normal text</div>
javascript
$(document).ready(function() {
showWelcome();
});
function foobar(i, overlay) {
if (i > -10) {
overlay.css('width', i);
setTimeout(function() {
foobar(i - 10, overlay);
}, 80);
}
else {
overlay.remove();
}
}
function showWelcome() {
var welcome = $('div.welcome');
welcome.append('<div class="overlay"></div>');
welcome.css('position', 'relative');
var overlay = $('.overlay');
overlay.css({
'width': welcome.css('width'),
'height': (welcome.outerHeight() + 5),
'position': 'absolute',
'right': '0',
'top': '-3px',
'background-color': '#FFF',
'z-index': '10'
});
var origWidth = overlay.css('width').replace(/px/g, '');
foobar(origWidth, overlay);
}