重新触发CSS3 animation和@keyframes定义的动画
结合CSS3的animation和@keyframes可以给元素定义动画,定义一个标题进入的动画如下:
只运行一次动画
scss
@keyframes my-animation {        
  from {
    opacity : 0;
    left : -500px;
  }
  to {
    opacity : 1;
    left : 0;
  }      
}
.run-animation {
  position: relative;
  animation: my-animation 2s ease;
}
#logo {
  text-align: center;
}@keyframes定义了效果,样式从左侧向右侧移动,由透明变为不透明。animation定义了动画,使用效果my-animation,耗时2秒,渐入。
html
<h1 id="logo" class="run-animation">
  你好(点击重新运行)
</h1>直接在元素上添加class run-animation,它只会运行一次。
重新运行动画
添加了动画的元素,只会在元素第一次渲染时才会触发动画,如果需要重新动画,需要对元素进行定位操作,步骤如下:
- 删除元素已添加的动画class
- 对元素做定位操作
- 添加原来的动画class
js如下:
var element = document.getElementById("logo");
// 监听触发动画的事件,如click
element.addEventListener("click", function(e){
  e.preventDefault;
  // 1、删除动画的class
  element.classList.remove("run-animation");
  // 2、改变元素的offsetWidth
  element.offsetWidth=element.offsetWidth;
  // 3、重新添加动画的class
  element.classList.add("run-animation");
}, false);需要注意的是再严格模式下,element.offsetWidth=element.offsetWidth是不生效的,替代方案:
void element.offsetWidth 
             
             
             
             
            