css动画效果代码案例
时间: 2023-06-04 09:04:34 浏览: 191
好的,我可以帮您展示一下 CSS 动画效果的代码案例,以下是一个简单的动画效果示例:
```
<!DOCTYPE html>
<html>
<head>
<title>CSS 动画效果示例</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: green;
position: relative;
animation-name: example;
animation-duration: 2s;
animation-timing-function: linear;
animation-iteration-count: infinite;
}
@keyframes example {
from {left: 0;}
to {left: 200px;}
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
```
上述代码用于创建一个绿色的方块,然后将其设置为相对定位,最后定义一个名为 `example` 的动画,让它在 2 秒内向右移动 200 像素,并且设置该动画的循环次数为无限次。
相关问题
css动画花瓣飘落案例
下面是一个简单的 CSS 动画花瓣飘落案例:
HTML 代码:
```
<div class="petals-container">
<div class="petal"></div>
<div class="petal"></div>
<div class="petal"></div>
<div class="petal"></div>
<div class="petal"></div>
<div class="petal"></div>
<div class="petal"></div>
<div class="petal"></div>
</div>
```
CSS 代码:
```
.petal {
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #ff8c94;
position: absolute;
top: -20px;
animation: fall 4s linear infinite;
}
.petal:nth-child(1) {
left: 10%;
animation-delay: 0s;
}
.petal:nth-child(2) {
left: 20%;
animation-delay: 0.5s;
}
.petal:nth-child(3) {
left: 30%;
animation-delay: 1s;
}
.petal:nth-child(4) {
left: 40%;
animation-delay: 1.5s;
}
.petal:nth-child(5) {
left: 50%;
animation-delay: 2s;
}
.petal:nth-child(6) {
left: 60%;
animation-delay: 2.5s;
}
.petal:nth-child(7) {
left: 70%;
animation-delay: 3s;
}
.petal:nth-child(8) {
left: 80%;
animation-delay: 3.5s;
}
@keyframes fall {
0% {
transform: translate(0, 0);
}
100% {
transform: translate(0, 800px);
}
}
.petals-container {
width: 100%;
height: 800px;
position: relative;
overflow: hidden;
}
```
解释:
这个案例中,我们首先创建了一个包含 8 个 div 元素的容器。这些 div 元素就是花瓣。我们使用了 nth-child 选择器来为每个花瓣设置不同的左侧位置和动画延迟时间。
然后,我们为每个花瓣设置了一个名为“fall”的动画。该动画将花瓣从初始位置向下移动 800 像素。
最后,我们将容器设置为相对定位,并将其高度设置为 800 像素,以便在动画中显示所有花瓣。我们还将 overflow 属性设置为 hidden,以便隐藏容器外的任何溢出内容。
此时,你可以在浏览器中查看这个案例,并看到花瓣飘落的效果。
css transitation 过渡案例
CSS transition(过渡)是CSS的一种动画效果,它可以在不同的CSS属性之间创建过渡效果。
以下是一个使用CSS transition实现的简单过渡案例:
HTML部分:
```html
<div class="box">我是一个盒子</div>
<button onclick="changeColor()">改变颜色</button>
```
CSS部分:
```css
.box {
width: 200px;
height: 200px;
background-color: blue;
transition: background-color 1s; /* 过渡属性及持续时间 */
}
.box:hover {
background-color: red; /* 鼠标悬停时的效果 */
}
button {
margin-top: 20px;
}
```
JavaScript部分:
```javascript
function changeColor() {
document.querySelector('.box').style.backgroundColor = 'green'; /* 点击按钮时改变盒子的背景颜色 */
}
```
以上代码实现了一个简单的过渡效果。当鼠标悬停在盒子上时,盒子的背景颜色会从蓝色过渡到红色,过渡时间为1秒。同时,点击按钮会将盒子的背景颜色改变为绿色。
这个案例展示了CSS transition的基本用法,可以通过设置transition属性来定义过渡的属性和持续时间。通过改变元素的属性值,就能实现漂亮的过渡效果,使页面变得更加生动。