首页 > 解决方案 > 继续一个无限的 CSS 动画,直到最后一帧才停止

问题描述

我有一个定义的 CSS 类spin,它在元素上创建一个简单的 CSS 动画微调器

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.spin {
  animation: spin .8s linear .15s infinite;
}

该类spin是通过 JavaScript 添加和删除的,但是当删除该类时,动画会突然剪切并显示第一帧。有没有办法让浏览器继续为元素设置动画,直到它到达最后一帧?

我厌倦了对“休息”元素(即没有类时相同的元素)进行多种组合animation-fill-mode或设置,但没有任何效果。任何想法如何使这项工作?animation-iteration-count: 1spin

标签: javascriptcsscss-animations

解决方案


如果我们把它和animationiteration事件结合起来,我们就可以做到。

const spin = document.querySelector(".spin");

let iterationCount = 0;
let isMouseover = 0;

spin.addEventListener('animationiteration', () => {
  iterationCount = 1;
  if (iterationCount && isMouseover) {
    spin.classList.remove("animation");
  } else {
    iterationCount = 0;
  }
});

spin.addEventListener("mouseover", () => {
  isMouseover = 1;
});

spin.addEventListener("mouseout", () => {
  isMouseover = 0;
  spin.classList.add("animation");
});
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.spin {
  height: 100px;
  width: 100px;
  background: yellow;
  border-right: 4px solid green;
  border-left: 4px solid red;
  border-top: 4px solid black;
  border-bottom: 4px solid blue;
}

.spin.animation {
  animation: spin .8s linear .15s infinite;
}
<div class="spin animation"></div>

也适用于点击:

const spin = document.querySelector(".spin");

let iterationCount = 0;
let isClicked = 0;

spin.addEventListener('animationiteration', () => {
  iterationCount = 1;
  if (iterationCount && isClicked) {
    spin.classList.remove("animation");
  } else {
    iterationCount = 0;
  }
});

spin.addEventListener("click", () => {
  if (isClicked) {
    isClicked = 0;
    spin.classList.add("animation");
  } else {
    isClicked = 1;
  }
});
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.spin {
  height: 100px;
  width: 100px;
  background: yellow;
  border-right: 4px solid green;
  border-left: 4px solid red;
  border-top: 4px solid black;
  border-bottom: 4px solid blue;
}

.spin.animation {
  animation: spin .8s linear .15s infinite;
}
<div class="spin animation"></div>


推荐阅读