js实现旋转按钮
实现旋转按钮的JavaScript方法
使用CSS动画结合JavaScript触发旋转效果,以下是具体实现方式:
HTML结构
<button id="rotateBtn">点击旋转</button>
CSS样式
#rotateBtn {
padding: 10px 20px;
background: #3498db;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: transform 0.3s ease;
}
.rotate {
transform: rotate(360deg);
}
JavaScript代码

const button = document.getElementById('rotateBtn');
button.addEventListener('click', () => {
button.classList.toggle('rotate');
// 动画结束后移除类名以实现多次旋转
button.addEventListener('transitionend', () => {
button.classList.remove('rotate');
}, { once: true });
});
使用CSS关键帧动画
更流畅的无限旋转效果实现:
CSS新增
@keyframes spinning {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spin {
animation: spinning 2s linear infinite;
}
JavaScript修改

button.addEventListener('click', () => {
button.classList.toggle('spin');
});
带进度控制的旋转
实现可暂停/继续的旋转效果:
JavaScript代码
let isRotating = false;
let animation;
button.addEventListener('click', () => {
if (!isRotating) {
let deg = 0;
animation = setInterval(() => {
deg = (deg + 5) % 360;
button.style.transform = `rotate(${deg}deg)`;
}, 20);
} else {
clearInterval(animation);
}
isRotating = !isRotating;
});
使用GSAP库实现高级旋转
安装GSAP后实现弹性旋转效果:
import { gsap } from "gsap";
button.addEventListener('click', () => {
gsap.to(button, {
rotation: 360,
duration: 1,
ease: "elastic.out(1, 0.5)"
});
});
以上方法可根据需求选择使用,CSS transition方案适合简单交互,GSAP方案适合需要复杂动画曲线的场景。






