2014-11-14 79 views
1

我剛剛在jQuery animate()上做了第一步。我試圖做一個演示類型的東西只是爲了練習,但我似乎無法使用animate()函數在動畫中間更改我的div的文本。jQuery animate()改變文本

這裏是我當前的代碼:

<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> 
<script> 
$(document).ready(function(){ 
    $("button").click(function(){ 
    var div=$("div"); 
    div.animate({left:'100px'},"slow"); 
    div.animate({fontSize:'3em'},"slow"); 
    div.animate({fontSize:'1em'},2000); 
    div.animate({opacity:'0'},"slow"); 
    //can I change the text with animation??? 
    div.animate({opacity:'1'},"slow"); 
    div.animate({left:'0px'},"slow"); 
    }); 
}); 
</script> 
</head> 
<body> 

<button>Start Animation</button> 
<div id='text'  style="background:#98bf21;height:100px;width:200px;position:absolute;">HELLO</div> 

</body> 
</html> 

是否存在,而混濁關閉我可以改變文本的實用方法,所以當動畫返回文本被改變?

+0

要替換文字? 'div.text('HI!');' – skobaljic 2014-11-14 22:04:48

+0

我個人已經完全停止使用Jquery的動畫,贊成GSAP和TweenJS。它的價值檢查他們兩個(GSAP更好的文本的東西) – Burdock 2014-11-14 22:05:36

+0

skobaljic,這將立即改變文本,而不是在動畫過程中。 – 2014-11-14 22:08:09

回答

2

您可以使用queue function排列更改。

$(document).ready(function(){ 
    $("button").click(function(){ 
     var div=$("div"); 
     div.animate({left:'100px'},"slow"); 
     div.animate({fontSize:'3em'},"slow"); 
     div.animate({fontSize:'1em'},2000); 
     div.animate({opacity:'0'},"slow"); 
     div.queue(function() { 
      div.html('New text'); 
      div.dequeue(); // This is necessary to continue the animation 
     }); 
     div.animate({opacity:'1'},"slow"); 
     div.animate({left:'0px'},"slow"); 
    }); 
}); 
+0

是的,它的工作,非常感謝 – 2014-11-14 22:33:59

+0

很高興我可以幫助! – rdubya 2014-11-14 22:38:17

0

您可以定義一個動畫監聽器,監聽範圍內改變你的文字:

$('div').animate(
    { opacity: 0 }, // and all the other properties you want to animate 
    { duration: 50, 
     step: function(left){ 
     // change text here after a particular progress 
     } 
}); 
0

這不是jQuery的,但您可以使用jQuery插件typed.js,這裏是an example

div.typed({ strings: ["HELLO", "It's me..."], typeSpeed: 0 });