javascript - 动画同步、光标和高亮

标签 javascript jquery html css animation

所以我几乎有了我的 code按我想要的方式工作,但无法让我的动画恰到好处地同步在一起。我正在尝试为突出显示文本的光标设置动画,然后单击按钮。问题是光标太慢或太快。我试图使这个动态以便无论文本有多长我仍然可以同步动画。我知道这可能只是一个数学问题,但我无法完全理解它。尝试将像素与毫秒相匹配的事情让我头晕目眩。在我拔掉所有头发之前请帮忙。谢谢。

这是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 的链接我一直在玩。

最佳答案

这可能会让我被否决,但也许你会得到更好的主意......
Fiddle Here

$(document).ready(function() {
$('p').click(function(){

    $('span').animate({'width':'100'},1000);
    $('.cursor').animate({marginLeft: 100},1000);
});
});

关于javascript - 动画同步、光标和高亮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13979394/

相关文章:

javascript - 无法实现流畅的javascript动画

javascript - 模拟背景大小 : cover in canvas

html - 背景图片,但带有不透明 CSS

javascript - 如何在html和javascript中显示用户上传的照片

java - 帮助从 HTML 表格中删除字段

javascript - MailApp指定邮箱发件人

javascript - 我们可以改变所选点的样式吗?

javascript - 如何将 CSS 应用于 Javascript 添加的元素

jquery - 使用 jQuery 从 HTML 元素名称获取键

Jquery将内容加载到div中