CSS3:animation

本文深入解析CSS动画的使用方法,包括简写与展开属性、动画事件、关键帧定义及硬件加速技巧,助您掌握平滑过渡与复杂动画效果的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 值,否则在之后加入(即位于其上层)的元素都会被加入到复合层计算中,造成性能浪费。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值