CSS3:animation

凌炜
2023-12-01

animation

简写属性:

#test {
	animation: test 2s linear 1s 1 normal;
	-webkit-animation: test 2s linear 1s 1 normal;
}

展开属性:

#test { 
	/*动画所使用的 keyframe 名称*/
    animation-name: test;
    /*动画时长*/
    animation-duration: 2s;   
     /*动效函数*/
     animation-timing-function: linear;
     /*延迟播放*/
    animation-delay: 1s;
    /*播放次数*/
    animation-iteration-count: 1;
     /*倒放动画*/
    animation-direction: normal;
    /* hack */
    -webkit-animation-name: test;
    -webkit-animation-duration: 2s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-delay: 1s;
    -webkit-animation-iteration-count: 1;
    -webkit-animation-direction: normal;
}

animation-name 属性绑定一个 keyframes 关键帧动画。

keyframes

@keyframes test {
	0%   {top: 0; transform: translate3d(0, 0, 0);}
	25%  {top: 200px; transform: translate3d(0, 0, 100px);}
	50%  {top: 100px; transform: translate3d(0, 0, 200px);}
	75%  {top: 200px; transform: translate3d(0, 0, 100px);}
	100% {top: 0; transform: translate3d(0, 0, 0);}
}
@-webkit-keyframes test {
	0%   {top: 0; -webkit-transform: translate3d(0, 0, 0);}
	25%  {top: 200px; -webkit-transform: translate3d(0, 0, 100px);}
	50%  {top: 100px; -webkit-transform: translate3d(0, 0, 200px);}
	75%  {top: 200px; -webkit-transform: translate3d(0, 0, 100px);}
	100% {top: 0; -webkit-transform: translate3d(0, 0, 0);}
}

animation事件

animationstart - CSS 动画开始后触发

document.getElementById('test').addEventListener('animationstart',function(){});
document.getElementById('test').addEventListener('webkitAnimationStart',function(){});

animationiteration - CSS 动画重复播放时触发

document.getElementById('test').addEventListener('animationiteration',function(){});
document.getElementById('test').addEventListener('webkitAnimationIteration',function(){});

animationend - CSS 动画完成后触发

document.getElementById('test').addEventListener('animationend',function(){});
document.getElementById('test').addEventListener('webkitAnimationEnd',function(){});

硬件加速

硬件加速CSS3 的 animation、transform、transitions 默认由浏览器的渲染引擎来执行。为了提升性能,需要开启硬件加速功能,即使用GPU进行渲染。通过下面的CSS规则可以出发触发硬件加速开启:

  1. translate3d
  2. rotate3d
  3. scale3d

同时,最好加上以下代码来防止屏幕闪烁(有吗?没发现啊~)

	-webkit-backface-visibility: hidden;
   -moz-backface-visibility: hidden;
   -ms-backface-visibility: hidden;
   backface-visibility: hidden;

最后,设置了触发 GPU 加速的元素需要单独设置其z-index 值,否则在之后加入(即位于其上层)的元素都会被加入到复合层计算中,造成性能浪费。

 类似资料: