所以我几乎有了我的code http://jsfiddle.net/bplumb/PBFWV/9/按照我想要的方式工作,但无法让我的动画正确同步。我正在尝试对光标进行动画突出显示文本,然后单击按钮。问题是光标要么太慢,要么太快。我正在尝试做这个dynamic以便无论文本有多长我仍然可以让动画同步。我知道这可能只是一个数学问题,但我无法完全理解它。尝试用毫秒来匹配像素让我头晕。在我拔掉所有头发之前请帮忙。谢谢。
这是html
<p><span id="container">I need to be highlighted one character at a time</span>
<input id="click" type="button" value="click me"/></p>
<img src="http://dl.dropbox.com/u/59918876/cursor.png" width="16"/>
这是CSS
#container{
font-size: 16px;
margin-right: 10px;
}
.highlight{
background: yellow;
}
img{
position: relative;
top: -10px;
}
还有 JavaScript
function highlight(){
var text = $('#container').text(); //get text of container
$('#click').css('border','none'); //remove the border
$('img').css('left', '0px'); //reset the cursor left
$('img').animate({left: $('#container').width() + 40}, text.length*70); //animation of cursor
$('#container').html('<span class="highlight">'+text.substring(0,1)+'</span><span>'+text.substring(1)+'</span>'); //set the first html
(function myLoop (i) {//animation loop
setTimeout(function () {
var highlight = $('.highlight').text();
var highlightAdd = $('.highlight').next().text().substring(0,1);;
var plain = $('.highlight').next().text().substring(1);
$('#container').html('<span class="highlight">'+highlight+highlightAdd+'</span><span>'+plain+'</span>');
if (--i) myLoop(i);// decrement i and call myLoop again if i > 0
}, 70)
})(text.length);
setTimeout(function () {
$('#click').css('border','1px solid black');
}, text.length*85);
}
highlight();
var intervalID = setInterval(highlight, $('#container').text().length*110);
//clearInterval(intervalID);
这是一个链接fiddle http://jsfiddle.net/bplumb/PBFWV/9/我一直在玩。