动画结束后的 CSS 过渡

evu*_*evu 7 css animation css-animations

我有一个 css 过渡,可以在悬停时移动元素,还有一个动画,可以在悬停时旋转元素。动画上有一个等于过渡持续时间的延迟,因此在过渡到正确位置后,动画就会开始。它工作得很好,但是,当我们将鼠标移开时,动画会停止,但不会向下过渡。

在我们鼠标移开并且动画结束后是否可以让它过渡回来?

您可以在此处查看示例:http ://codepen.io/jhealey5/pen/zvXBxM

简化的代码在这里:

    div {
        width: 200px;
        height: 200px;
        margin: 40px auto;
        background-color: #b00;
        position: relative;

        &:hover {
            span {
                transform: translateY(-60px);
                animation-name: rotate;
                animation-duration: 1s;
                animation-delay: .5s;
                animation-iteration-count: infinite;
                animation-direction: alternate;
            }
        }
    }

    span {
        position: absolute;
        width: 20px;
        height: 20px;
        background-color: #fff;
        bottom: 10px;
        left: 0;
        right: 0;
        margin: auto;
        transition: .5s;
    }

    @keyframes rotate {
        from {
            transform: translateY(-60px) rotate(0);
        }
        to {
            transform: translateY(-60px) rotate(-90deg);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Rve*_*urt 6

我已经分叉了你的项目并对其进行了调整,使其可以正常工作。你可以在这里找到它。

我改变的内容如下:

我给白色方块一个起始位置top: 150px并让它在 上hover得到div一个top: 0。跨度得到 a transition: top .5s,然后它会在悬停时进入,并在鼠标离开时top: 0;返回。top: 150px;

我已经从动画中删除了,因为这会在开始translateY(-60px);时将其向上移动得更多。animation

这是您的新 CSS:

div {
    width: 200px;
    height: 200px;
    margin: 40px auto;
    background-color: #b00;
    position: relative;

    &:hover {
        span {
            top: 0px;
            animation: rotate 1s infinite .5s alternate;
            animation-direction: alternate;
        }
    }
}

span {
    position: absolute;
    width: 20px;
    height: 20px;
    background-color: #fff;
    bottom: 10px;
    left: 0;
    right: 0;
    top: 150px;
    margin: auto;
    transition: top .5s;
}

@keyframes rotate {
    from {
        transform: rotate(0);
    }
    to {
        transform: rotate(-90deg);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:问题是动画是基于时间的而不是基于动作的,这意味着一旦触发动画,计时器就会开始运行,并且它将运行所有动画,keyframes直到设定的时间过去。悬停入和悬停出没有任何效果,只是计时器可以提前停止,但此后动画将不会继续(或反转,您想要的)。是基于操作的,这意味着每次发生transition操作(例如 )时都会触发它。:hover在 上:hover,这意味着需要 0.5 秒才能到达top:0,当悬停结束时,需要 0.5 秒才能到达top:150px

我希望上面的补充有意义:)

正如你所看到的,我还在你的等中清理了一些animation-name:,因为它可以合并成一行。