用css+js 实现一个小人流泪动画 点击按钮之前 动画未开始 点击按钮之后 动画开始
时间: 2023-08-23 16:06:48 浏览: 41
好的,下面是代码实现:
HTML 代码:
```html
<div id="person">
<div id="head"></div>
<div id="body"></div>
<div id="left-eye"></div>
<div id="right-eye"></div>
<div id="mouth"></div>
<div id="tear"></div>
</div>
<button id="startBtn" onclick="startAnimation()">开始动画</button>
```
CSS 代码:
```css
#person {
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -100px;
}
#head {
width: 100px;
height: 100px;
border-radius: 50%;
background: #f5c5c5;
position: relative;
overflow: hidden;
}
#body {
width: 20px;
height: 60px;
background: #f5c5c5;
margin: 0 auto;
position: absolute;
top: 100px;
left: 50%;
margin-left: -10px;
}
#left-eye,
#right-eye {
width: 20px;
height: 20px;
background: #fff;
border-radius: 50%;
position: absolute;
top: 30px;
left: 30px;
box-shadow: 0 0 5px #000;
}
#right-eye {
left: 50px;
}
#mouth {
width: 40px;
height: 10px;
background: #000;
position: absolute;
top: 60px;
left: 30px;
border-radius: 5px;
}
#tear {
width: 20px;
height: 20px;
position: absolute;
top: 70px;
left: 40px;
border-radius: 50%;
background: #fff;
box-shadow: 0 0 5px #000;
display: none;
}
#tear:before,
#tear:after {
content: '';
display: block;
width: 10px;
height: 10px;
border-radius: 50%;
background: #000;
position: absolute;
top: 5px;
}
#tear:before {
left: 0;
}
#tear:after {
right: 0;
}
```
JavaScript 代码:
```javascript
function startAnimation() {
var tear = document.getElementById('tear');
tear.style.display = 'block';
setTimeout(function() {
tear.classList.add('fall');
}, 500);
}
```
解释一下代码:
首先,我们使用 HTML 创建了一个小人的结构,并在页面中放置一个按钮。
其次,我们使用 CSS 对小人进行样式设置,包括小人的身体、头部、眼睛、嘴巴、泪水等部分的样式。
最后,我们使用 JavaScript 来实现点击按钮后,泪水从小人眼角滑落的动画效果。我们给泪水添加了一个 `fall` 类,这个类中包含了泪水下落的动画效果。当点击按钮后,我们通过 `setTimeout` 函数等待 500ms 后再添加 `fall` 类,从而实现了点击按钮后动画效果的开始。