简体   繁体   English

我如何制作动画 <div> ?

[英]How do I animate a <div>?

I am trying to keep the <div> centered on the screen but this fails. 我试图将<div>保持在屏幕中央,但这失败了。

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. 因此,主要是在第二个动画之后,其中<div>在每个方向上增长200px,顶部和左侧与第一个动画保持相同。 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. 您从self.outerHeight()获得的值是当前的绝对值(不包括添加的量),因为jQuery将缓慢增加大小以产生动画效果。

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. 您的第二个动画都同时执行,因此self.outerHeight()等于执行时的外部高度,而不是宽度/高度的动画完成时。

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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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