简体   繁体   中英

Animate DIV size using jQuery without knowing the final size

I have a DIV with content that is inserted dynamically using jQuery. I want that div to appear as if it was enlarged from size 0px to the size it suppose to take when the div is rendered with its content.

The content is text, so I have no information about the size it will take when it is appended to the document. I know how to animate the div using jQuery Animate when I know the final size, but don't know how to do it when I don't know it.

if I use width: "+=10" for example, I get a div that is larger than the one that I get without animating. Thanks.

Insert your item, save the width and the height, and then set the width and the height of the item to zero. This will happen too quickly to be visible, and you'll have the final width and height values you need for animation.

Live Demo

var $div = $('<div>', {
    text: <your text>
});

// <append your element>

var width = $div.width();
var height = $div.height();

$div.css({
    width: 0,
    height: 0
});

$div.animate({
    width: width,
    height: height
}, {
    duration: 'slow',
    easing: 'linear'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM