jQuery animate() change text

2020-04-17 21:03发布

I'm just now giving my first steps on jQuery animate(). I'm trying to make a presentation type thing just to practice, but I can't seem to be able to change the text of my div in the middle of the animation using the animate() function.

Here's my current code:

<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>

Is there a practical way I can change the text while the opacity is turned off, so when the animation returns the text is changed?

3条回答
ゆ 、 Hurt°
2楼-- · 2020-04-17 21:36

You can define an animation-listener and change your text within the listener:

$('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
      }
});
查看更多
你好瞎i
3楼-- · 2020-04-17 21:46

You can use the queue function to queue up the change.

$(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");
    });
 });
查看更多
家丑人穷心不美
4楼-- · 2020-04-17 21:56

This is not available in jQuery, but you can use the jQuery plugin typed.js, here is an example:

  div.typed({ strings: ["HELLO", "It's me..."], typeSpeed: 0 });
查看更多
登录 后发表回答