CSS3@keyframes规则和animation动画

html-css032

CSS3@keyframes规则和animation动画,第1张

CSS3中新增了动画相关的属性,其中@keyframes规则用于设置创建动画,其原理其实就是将一套css样式逐渐变成另外一套css样式,在@keyframes中可以使用百分比表示动画进度对应的样式,0% 是动画的开始样式,100% 动画的结束样式,每个样式可以称为"关键帧样式",每个动画可以包含很多帧,每一帧可以设置一个或多个样式。语法格式: @keyframes 动画名:{0%:{css样式} ... 100%:{css样式}} ,其中关键帧合法值是0-100%,from与 0% 相同,to与 100% 相同

使用@keyframes定义了动画,那如何使用呢?

那就得在对应要使用该动画的元素上添加animation属性

animation是一个复合属性,是所有动画属性的缩写,除animation-play-state

1. animation-name 动画名,表示要应用哪个动画

2. animation-duration 动画完成一个周期所花费的时间(秒或毫秒数),默认0

3. animation-timing-function 表示动画速度曲线,常用关键字linear、ease、ease-in、ease-out、ease-in-out,默认是ease。还可以使用cubic-bezier(n,n,n,n)设置

4. animation-delay 动画延迟时间,默认0

5. animation-iteration-count 动画播放次数,默认1 只播一次

6. animation-direction 设置动画在下个播放周期是否逆转方向,默认是 "normal"正常播放,alternate轮流反向播放

7. animation-fill-mode 用于设置动画填充模式,none 不改变默认行为;forwards当动画完成后,保持最后一个属性值(在最后一个关键帧中定义);backwards在 animation-delay 所指定的一段时间内,在动画显示之前,应用开始属性值(在第一个关键帧中定义);both向前和向后填充模式都被应用

8. animation-play-state 设置动画播放状态,paused动画已暂停,running是默认值,表示动画正在运行播放

你要出发某个事件,才能再次执行动画吧,或通过伪类,或用JS.

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>无标题文档</title>

<style>

.test{

    display:block

    width:100px

    height:20px

    border:1px solid #ff0000

    -webkit-animation:f0 2s 0.5s 1  linear

    -webkit-animation-fill-mode:forwards

}

.test-high{

    width:500px

    -webkit-animation:f1 2s 0.5s 1  linear

    -webkit-animation-fill-mode:forwards

}

@-webkit-keyframes f0{

    0%{width:100px}

    100%{width:500px}

}

@-webkit-keyframes f1{

    0%{height:20px}

    100%{height:200px}

}

</style>

</head>

<body>

<div>

<div class="test">我会长大</div>

<button type="button" onclick="goHigher()">变高一点</button>

<script>

 function goHigher(){

  document.getElementsByClassName("test")[0].className = "test test-high"

 }

</script>

</body>

</html>

这里div.test会变宽到500px停住,当给他添加上test-high类时,会保持500px的宽度,在变高。

这可能就是你要的,关键是再下一个动画开始前将样式调整到上一个动画结束时一样。