CSS 动画风车:使用按钮控制转动速度
<div class='windmill-container'>
<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>
</div>
<p><button id='start-btn'>开始</button>
<button id='accelerate-btn'>加速</button>
<button id='decelerate-btn'>减速</button>
<button id='stop-btn'>结束</button></p>
<style>
.windmill-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.windmill {
position: relative;
width: 200px;
height: 200px;
transform-origin: center;
animation: rotate 0s linear infinite;
}
.blade {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
transform-origin: bottom center;
}
.blade-1 {
transform: rotate(0deg);
background-color: #f44336;
}
.blade-2 {
transform: rotate(90deg);
background-color: #4caf50;
}
.blade-3 {
transform: rotate(180deg);
background-color: #2196f3;
}
.blade-4 {
transform: rotate(270deg);
background-color: #ffeb3b;
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>
<script>
const windmill = document.querySelector('.windmill');
const startBtn = document.getElementById('start-btn');
const accelerateBtn = document.getElementById('accelerate-btn');
const decelerateBtn = document.getElementById('decelerate-btn');
const stopBtn = document.getElementById('stop-btn');
let speed = 0;
startBtn.addEventListener('click', () => {
windmill.style.animation = `rotate ${10 - speed}s linear infinite`;
});
accelerateBtn.addEventListener('click', () => {
if (speed < 9) {
speed++;
windmill.style.animationDuration = `${10 - speed}s`;
}
});
decelerateBtn.addEventListener('click', () => {
if (speed > 0) {
speed--;
windmill.style.animationDuration = `${10 - speed}s`;
}
});
stopBtn.addEventListener('click', () => {
windmill.style.animation = 'none';
speed = 0;
});
</script>
<p>首先,我们通过querySelector方法获取到风车元素,然后通过getElementById方法获取到四个按钮元素。</p>
<p>接着,我们定义一个变量speed来表示风车的速度,初始值为0。</p>
<p>在点击【开始】按钮时,我们将风车的animation属性设置为rotate 10s linear infinite,其中10s是转一圈所需的时间,linear表示匀速旋转,infinite表示无限循环。这样,点击开始按钮后,风车就开始转动了。</p>
<p>在点击【加速】按钮时,我们首先判断当前速度是否小于9,如果是,则将速度加1,并将风车的animationDuration属性设置为10 - speed秒,也就是转一圈所需的时间随着速度的增加而变短,这样就实现了加速的效果。</p>
<p>在点击【减速】按钮时,我们首先判断当前速度是否大于0,如果是,则将速度减1,并将风车的animationDuration属性设置为10 - speed秒,也就是转一圈所需的时间随着速度的减少而变长,这样就实现了减速的效果。</p>
<p>在点击【结束】按钮时,我们将风车的animation属性设置为none,这样风车就停止转动了,并将速度重置为0。</p>
<p>最后,我们通过addEventListener方法为四个按钮添加点击事件监听器,实现了按钮控制风车转动的效果。</p>
原文地址: https://www.cveoy.top/t/topic/jQXN 著作权归作者所有。请勿转载和采集!