简述css 动画如何实现 ?
参考答案:
CSS 动画主要通过 transition
和 @keyframes
规则来实现。
- CSS Transition(过渡):
CSS Transition 是一种使元素从一种样式逐渐改变为另一种样式的方法。要实现 CSS Transition,需要以下两个步骤:
- 指定要添加动画的 CSS 属性;
- 指定动画的持续时间。
例如,你可以让一个元素的背景色在 2 秒内从红色变为黄色:
div {
width: 100px;
height: 100px;
background: red;
transition: background 2s;
}
div:hover {
background: yellow;
}
在这个例子中,当你把鼠标悬停在 div 上时,它的背景色会在 2 秒内从红色平滑过渡到黄色。
- CSS Animation(动画):
CSS Animation 是更强大的动画工具,它允许你创建更复杂的动画效果,包括关键帧动画。要实现 CSS Animation,你需要使用 @keyframes
规则。
例如,你可以创建一个动画,使元素在 2 秒内从红色变为黄色,然后再变回红色:
@keyframes color-change {
0% {
background: red;
}
50% {
background: yellow;
}
100% {
background: red;
}
}
div {
width: 100px;
height: 100px;
background: red;
animation: color-change 2s infinite;
}
在这个例子中,@keyframes
规则定义了一个名为 color-change
的动画,动画会在 0%、50% 和 100% 的时间点改变元素的背景色。然后,animation
属性将 color-change
动画应用于 div 元素,并设置动画的持续时间为 2 秒,且无限循环。
你还可以设置 animation-direction
、animation-timing-function
、animation-delay
和 animation-iteration-count
等属性,以进一步控制动画的行为。
以上就是 CSS 动画的基本实现方法。你可以通过结合使用 transition
和 @keyframes
,以及调整各种动画属性,来创建出各种复杂且吸引人的动画效果。