1

诚然,我是 jQuery 的新手,但我知道一点 javascript,我正在尝试用几个动画来为 div 设置动画。

我希望 div 首先移动到页面的中心然后我希望它在到达中心后翻转然后展开。

我遇到的麻烦是使用该.animate()方法更改 div 的topleft属性以使其居中。


问题是 moveToCenter 函数中的 .animate 方法实际上并没有动画到中心的移动,它只是跳过动画部分(属性更改,但更改不是动画)并继续进行翻转和其余部分。

有人能告诉我为什么会这样/我哪里出错了吗?

以及如何(如果有的话)修复?


的HTML

<div id="flip" style="background-color:#ff0000;
               width:200px;
               height:200px;
               position:absolute">

  <h4> printf("Hello World"); </h4>
</div>

JS

function moveToCenter()
{
    $('#flip').animate({'top':'300','left':'300'});
}

$(document).ready(function() {
    $('#flip').click( function() {

            moveToCenter(); //function that is supposed to moves the div to the center

            $(this).flip({
                    content: 'Scanf()',
                    color: '#00FF00',
                    direction: 'lr',
                    onEnd:  function(){ $('#flip').animate({ 
                    'height' : '400', 'width': '300'
                    }       
                    ,'500','swing');

                    lol(); //Another function that does some other animations
                    }
                });
            });
        });
4

2 回答 2

1

如果要在动画完成后翻转,请添加如下回调:

function moveToCenter(done){
    $('#flip').animate({'top':'300','left':'300'}, done);
}

该函数将done在动画完成时调用该方法。所以现在你只需要传递它:

moveToCenter(function() {
    // now the animation is done, move on
    $(this).flip({ //... etc
于 2012-11-27T12:36:33.580 回答
1

尝试:

function flipElem() {
    $('#flip').flip({
        content: 'Scanf()',
        color: '#00FF00',
        direction: 'lr',
        onEnd: function() {
            $('#flip').animate({
                'height': '400',
                'width': '300'
            }, '500', 'swing');

        }
    });
}

function moveToCenter(elem) {
    $(elem).animate({
        'top': '300',
        'left': '300'
    }, flipElem);
}

$(document).ready(function() {
    $('#flip').click(function() {
        moveToCenter(this);
    });
});​

移动到中心动画完成后立即注册回调。如果你在它完成之前这样做,它可能会产生奇怪的效果,但仍然很有可能。

小优化:将元素传递给 flipElem 而不是再次使用 $('#flip'),类似于 moveToCenter(this)

于 2012-11-27T13:03:50.213 回答