使用按钮控制风车转动结合css动画的风车作业完成如下任务:页面打开时风车不转动点击【开始】按钮时风车开始转动点击【加速】按钮后风车转动越来越快点击【减速】按钮后风车转动越来越慢点击【结束】按钮后风尘停止转动
HTML代码:
<div class="windmill">
<div class="blade blade-1"></div>
<div class="blade blade-2"></div>
<div class="blade blade-3"></div>
<div class="blade blade-4"></div>
<div class="center"></div>
</div>
<button id="startBtn">开始</button>
<button id="speedUpBtn">加速</button>
<button id="slowDownBtn">减速</button>
<button id="stopBtn">结束</button>
CSS代码:
.windmill {
position: relative;
width: 200px;
height: 200px;
margin: 50px auto;
}
.blade {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
background-color: #0077be;
transform-origin: center center;
animation-name: rotate;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
.blade-1 {
transform: rotate(0deg);
}
.blade-2 {
transform: rotate(90deg);
}
.blade-3 {
transform: rotate(180deg);
}
.blade-4 {
transform: rotate(270deg);
}
.center {
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
background-color: #fff;
border-radius: 50%;
transform: translate(-50%, -50%);
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.windmill.stop .blade {
animation-play-state: paused;
}
.windmill.slow .blade {
animation-duration: 4s;
}
.windmill.fast .blade {
animation-duration: 1s;
}
JavaScript代码:
const windmill = document.querySelector('.windmill');
const startBtn = document.querySelector('#startBtn');
const speedUpBtn = document.querySelector('#speedUpBtn');
const slowDownBtn = document.querySelector('#slowDownBtn');
const stopBtn = document.querySelector('#stopBtn');
startBtn.addEventListener('click', () => {
windmill.classList.remove('stop');
});
speedUpBtn.addEventListener('click', () => {
windmill.classList.remove('slow');
windmill.classList.add('fast');
});
slowDownBtn.addEventListener('click', () => {
windmill.classList.remove('fast');
windmill.classList.add('slow');
});
stopBtn.addEventListener('click', () => {
windmill.classList.add('stop');
});
解释:
- 首先,我们需要获取到风车的DOM元素和四个按钮的DOM元素,这里使用了
querySelector方法。 - 接着,分别为四个按钮添加了
click事件监听器,当点击按钮时执行相应的操作。 - 在点击【开始】按钮时,我们需要移除
stop类,使风车开始转动。 - 在点击【加速】按钮时,我们需要移除
slow类并添加fast类,使风车转动速度加快。 - 在点击【减速】按钮时,我们需要移除
fast类并添加slow类,使风车转动速度减慢。 - 在点击【结束】按钮时,我们需要添加
stop类,使风车停止转动。 - 最后,在CSS中定义了三个类,分别是
stop、slow、fast,用来控制风车的动画效果。当添加stop类时,风车的动画会暂停;当添加slow类时,风车的动画会变慢;当添加fast类时,风车的动画会变快
原文地址: https://www.cveoy.top/t/topic/cjeQ 著作权归作者所有。请勿转载和采集!