连续动画功能与关闭

时间:2015-03-08 00:56:26

标签: jquery

嗯,有点难以解释所以我会保持简单(加上我已经24小时了:O)

这个想法是,你将鼠标放在父母身上并且它的图像反弹。我希望弹跳是连续的直到mouseout事件。我正在尝试用jQuery改进,所以我正在尝试这个:

$.fn.bounce=function(){
    return this.each(function(){
        var self=this;
        this.original=$(this).css('position');
        if(this.original!='relative')$(this).css({'position':'relative'});
        //Not sure if using queues would be better? 
        $(this).animate({top:-20},200);
        $(this).animate({top:0},100);
        $(this).animate({top:-10,}100);
        $(this).animate({top:0,}50);
        $(this).animate({top:-5},25);
        $(this).animate({top:0},0,function(){$(this).css({'position':self.original});
    });
};

$('#parent').mousein(function(){$('img','#parent').bounce();});

如何让动画继续播放直到mouseout? :S我迷路了,甚至不知道从哪里开始寻找DX

1 个答案:

答案 0 :(得分:0)

我会这样做:

声明一个标志bouncing=falsemouseover(不是mousein)上,将标记设置为true并运行一个永久退回的函数 bouncing===true

mouseout上,将标志设置为false

<强> JS

var bouncing = false;
var bounce = function () {
    //upward animation for .1 sec
    $('#parent').find('img').animate({top: "55px"}, 100, function () {
        //downward animation for.1 sec
        $(this).animate({top: "95px"}, 100, function () {
            if (bouncing === true) {
                //keep bouncing if the flag is set
                return bounce();
            } else {
                //otherwise we are done bouncing
                return true;
            }
        });
    });
};
$('#parent').mouseover(function () {
    //if we are already bouncing, do nothing
    if (bouncing === true) {
        return false;
    } else {
        //else set the flag true, and start bouncing!
        bouncing = true;
        bounce();
    }
});
$('#parent').mouseout(function () {
    //stop bouncing on mouse out
    bouncing = false;
});

<强> CSS

#parent{
    width:300px;
    height:300px;
    border:2px solid black;
    border-radius:4px;
    position:relative;
}
#parent > img{
    position:absolute;
    top:75px;
    left:75px;
}

<强> HTML

<div id=parent>
    <img src=someimg.jpg>
</div>

小提琴: http://jsfiddle.net/qvsyjqec/

这是基本的想法,你可以通过调整动画速度,搞乱缓和/关键帧或其他一些东西来使它变得更强大