简体   繁体   中英

How do I animate a <div>?

I am trying to keep the <div> centered on the screen but this fails.

Here is the code:

var self = $(this);
self.animate({
    'top': ($(window).height() / 2) - (self.outerHeight() / 2),
    'left': ($(window).width() / 2) - (self.outerWidth() / 2)
}, 600, 'swing', function () {
    self.animate({
        'width': '+=200px',
        'height': '+=200px', 
        'top': ($(window).height() / 2) - (self.outerHeight() / 2), //NO UPDATE
        'left': ($(window).width() / 2) - (self.outerWidth() / 2) //NO UPDATE
    }, 600, 'linear');
});

So mainly after the second animation where the <div> grows by 200px on each direction, top and left stay the same from the first animation. I'd like the position to update as well.

What can be done here?

Do take into consideration than when running the following code:

'top': ($(window).height() / 2) - (self.outerHeight() / 2), //NO UPDATE
'left': ($(window).width() / 2) - (self.outerWidth() / 2) //NO UPDATE

The value you get from self.outerHeight() is the absolute current value (without the added amount) as jQuery will increment the size slowly to give the impression of an animation.

To make it work you must add the amount manually:

'top': ($(window).height() / 2) - ((self.outerHeight()+200) / 2), // notice the +200

Your second animation is all executing at the same time, so self.outerHeight() is equal to the outerheight at the time of execution, not when the animation of width/height is done.

You should probably set it to:

self.animate({
            'width': '+=200px',
            'height': '+=200px', 
            'top': ($(window).height() / 2) - ((self.outerHeight() +200 )/ 2), //NO UPDATE
            'left': ($(window).width() / 2) - ((self.outerWidth() +200 )/ 2) //NO UPDATE
        }, 600, '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