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

Per*_*son 8 performance animation css3 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>
Run Code Online (Sandbox Code Playgroud)

使用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');
});
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

小智 4

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