javascript - 继续一个无限的 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: 1
spin
解决方案
如果我们把它和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>
推荐阅读
- javascript - 当一个 HTML 文件中有 2 个页面时,HTML 内置表单验证不显示错误消息
- spring-boot - 将 EJB 项目合并到 Spring Boot 中
- java - 提高 defineClass() 的性能,以重复多次调用以从字节码加载 Java 类
- javascript - Luxon DateTime:为扩展添加类型
- python - 结果按钮消失并且条件代码不起作用
- python - 在 Django 中按字段区分分组
- node.js - 添加“less”和“less-loader”模块后如何修复损坏的vuejs项目
- pytest - 如何将场景特定的参数传递给 pytest bdd after_scenario 挂钩?
- python - 熊猫使用 loc 更改特定行的数据集值
- c# - 未修改的 asp.net 模板中的 NullReferenceException (Visual Studio)