如何运行一次CSS3关键帧动画,并且仅在触发时?

时间:2013-10-25 08:30:03

标签: performance css3 animation css-transitions css-animations

我想实现一个HTML5动画,它不仅仅涉及将项目从A点移动到B点。这就是我考虑使用关键帧而不是转换的原因。但是,我只想让动画运行一次,并且仅在触发时运行。

问题是双重的: 1)动画结束后,项目返回到开始位置。有没有办法让它保持在最终位置,直到另行通知? 2)以后有没有办法从Javascript重启动画?

我看到的另一个可能的解决方案是使用onTransitionEnd事件链接一些转换。

考虑到性能,这里最好的解决方案是什么?我只针对Webkit浏览器,包括移动设备。

编辑:基于@ Christofer-Vilander的评论,我做了JSfiddle,基本上做了我想要的。谢谢!

HTML:

<button id="start">Start</button> <button id="reset">Reset</button>
<br/>
<div id="ball" class="ball"></div>

使用Javascript:

document.getElementById('start').addEventListener('click', function(e) {
    document.getElementById('ball').classList.add('remove');
});

document.getElementById('reset').addEventListener('click', function(e) {
    document.getElementById('ball').classList.remove('remove');
});

CSS:

.ball {
    width:100px;
    height:100px;
    border-radius:100px;
    background-color:darkred;
    position:absolute;
    top:100px;
    left:200px;
}

@-webkit-keyframes slide {
    from { top:100px; left:200px; }
    to { top:100px; left:-100px; }
}

.remove {
    animation: slide 1s linear;
    -webkit-animation: slide 1s linear;
    -webkit-animation-iteration-count: 1;
    -webkit-animation-fill-mode: forwards;
}

1 个答案:

答案 0 :(得分:4)

使用Javascript在html元素中添加一个类,并为此类添加所需的css动画规则集。使用animation-fill-mode: forwards;让动画运行一次。 然后,从元素中删除该类以重新运行动画onClick。