我有一个可以在点击时旋转的框:
.box{
width: 200px;
height: 200px;
background:red;
transition: all 1s;
}
.box.spin{
animation: spin 5s infinite linear;
}
当您再次单击它时,我希望它旋转或停止旋转。似乎它会立即恢复到初始位置:
https://codepen.io/EightArmsHQ/pen/OaoPKm?editors=0100
是否有一种方法可以实现而无需用过渡替换动画?
答案 0 :(得分:2)
如何使用animation-play-state
属性?
.box{
animation: spin 5s infinite linear; // add this here
animation-play-state: paused; // pause animation by default
}
.box.spin{
animation-play-state: running; // play animation
}
https://codepen.io/frantisekvrab/pen/YROXaZ
如果您想完成旋转,我假设您必须使用更多的JS或CSS过渡。
答案 1 :(得分:0)
“旋转”是指让它朝另一个方向旋转吗?如果是这样,您可以执行以下操作:
window.onload = ()=>{
let box = document.querySelector('.box');
box.addEventListener('click', function(){
this.classList.toggle('spin')
this.classList.toggle('spin-reverse')
});
}
@keyframes spin{
0%{
transform: rotate(0deg);
}
100%{
transform: rotate(360deg);
}
}
html, body{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.box{
cursor: pointer;
width: 200px;
height: 200px;
background:red;
transition: all 1s;
box-sizing: border-box;
color: #fff;
display: flex;
padding: 30px;
text-align: center;
align-items: center;
justify-content: center;
user-select: none;
}
.box.spin{
animation: spin 5s infinite linear;
}
.box.spin-reverse {
animation: spin 5s infinite linear reverse;
}
<div class="box spin" id="box">
Click to toggle animation
</div>
另外,这是working example:)