Animate appended text
How would I got about animating appended text to a div tag. For eample the div starts out with no text in it. When a user clicks a button it apends text to the div which the div expands to the height of the text. Instead of just expanding instantly. I would like to 开发者_开发知识库animate the expand.
Would I first need to store the height of the div when the text is appended to the div. Then set the height of the div to 0 and then animate the height to the stored text height, or is there a more efficient way.
Updated explanation The text will populate about 4 lines in the div when added. Take 3 divs, a top div, center div which is my empty div waiting to be filled. Then a bottom div. With no text in my middle div it looks like the top and bottom div are close to each other. With 4 lines of text added to the middle div the bottom div instantly gets pushed down by the height of the new text in the middle div. I want to show this in animation as opposed to instantly happening.
If the div starts out with no text in it, then simply reveal it then slide it down once it has been filled with text. E.g.:
$("#myDiv").html(html).slideDown("slow");
assuming the div starts out hidden, such as:
<div id="myDiv" style="display:none"></div>
One suggestion: Don't animate the height, just animate the font size and let the height naturally grow to fit. Example:
<div></div>
<input>
<button>Add text</button>
$('button').click(function(){
$('div')
.text($('input').val())
.css({fontSize: 0})
.animate({
fontSize: "24px",
});
});
Demo: http://jsfiddle.net/UHcp6/
Really it depends on what exact behavior you want, this is just one way to do it.
Appending additional text afterwards seems like a bad case for animation, but if you want to append text, just store the original value in a variable with text()
, then use text(var + your_text)
.
精彩评论