要使CSS3动画一直旋转,并在暂停时保持最后的角度,您可以使用animation-play-state: paused;
属性来暂停动画,并使用animation-fill-mode: forwards;
来保留最后的状态。
CSS代码:
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.rotating-element {
animation: rotate 2s linear infinite;
animation-play-state: running; /* 默认运行动画 */
animation-fill-mode: forwards; /* 在动画结束时保留最后的状态 */
}
.rotating-element.paused {
animation-play-state: paused; /* 添加一个类来暂停动画 */
}
HTML代码:
<div class="rotating-element">旋转我</div>
<button onclick="toggleRotation()">暂停/继续</button>
<script>
function toggleRotation() {
var element = document.querySelector('.rotating-element');
element.classList.toggle('paused');
}
</script>
在这个例子中,一个元素被赋予了一个无限循环的旋转动画。当点击按钮时,会通过JavaScript切换.paused
类,暂停或继续动画。由于animation-fill-mode
设置为forwards
,动画暂停时会保留在最后的角度。