CSS动画动态起始状态

时间:2016-09-24 09:34:48

标签: jquery css3 animation

我有两个动画,一个在悬停时触发,另一个在退出悬停时触发。我想学习:

如何启动悬停动画停止的退出悬停动画,无论其进展有多远。

OR

即使退出提前悬停,动画也会持续到最后,然后立即执行退出悬停动画。

目前,如果您快速退出悬停,它会跳转到退出悬停动画的起始位置。

Fiddle here

HTML

<div class="image-container">
        <img src="https://dummyimage.com/200x200/000/fff">
</div>

CSS

.image-container {
  margin: 50px;
}
img {
  width: 100px;
  -webkit-transform: rotate(-45deg);
}
img.over {
  -webkit-animation: enlarge .5s cubic-bezier(.42,0,.8,1) both,
         enlarge-2 .25s cubic-bezier(.2,0,.3,1) .5s forwards;
}
img.out {
  -webkit-animation-name: shrink;
  -webkit-animation-duration: .5s;
  -webkit-animation-timing-function: ease-in-out;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-fill-mode: both;
  -webkit-animation-direction: forwards;
}
@-webkit-keyframes enlarge {
  from {transform: rotate(-45deg) scale(1);}
  to {transform: rotate(0deg) scale(1.5);}
}
@-webkit-keyframes enlarge-2 {
  from {transform: scale(1.5);}
  to {transform: scale(1.3);}
}
@-webkit-keyframes shrink {
  from {transform: rotate(0deg) scale(1.3);}
  to {transform: rotate(-45deg) scale(1);}
}

的JavaScript

$("img").hover(
    function () {
        $(this).removeClass('out').addClass('over');
    },
    function () {
        $(this).removeClass('over').addClass('out');
    }
);

1 个答案:

答案 0 :(得分:0)

下面的代码未经测试,但显示了使用信号量的想法,并在动画开始时安排超时以在动画结束时释放信号量。

function hoverAnimationHandler(context, intervalLength) {
    var alreadyRunning = false;
    var currentEvent = undefined;
    var scheduledAction = undefined;
    function runEvent(currentContext, event) {
        if (alreadyRunning) {
            if (currentEvent !== event) {
                scheduledAction = event;
            }
        } else {
            alreadyRunning = true;
            currentEvent = event;
            event(currentContext);
            setTimeout(function() {
                currentEvent = undefined;
                alreadyRunning = false;
            }, intervalLength);
        }
    }
    function hover(currentContext) {
        currentContext.removeClass("out").addClass("hover");
    }
    function unHover(currentContext) {
        currentContext.removeClass("hover").addClass("out");
    }
    context.hover(function() {
        runEvent($(this), hover);
    }, function() {
        runEvent($(this), unHover);
    });
}