javascript - 如何在不破坏原始标签对象的情况下停止和重置动画?
问题描述
我正在尝试将对象的动画重置为其初始点,以便我可以从头开始重新启动它。
function swap_animation(node, from, to) {
let t = node.style.animationDuration;
node.style.animationDuration = "0s";
node.style.animationPlayState = "initial";
setTimeout(function(){
node.style.animationDuration = t;
node.classList.remove(from);
node.classList.add(to);
}, 10);
}
function grow() {
let node = document.getElementById("item");
swap_animation(node, "shrink", "grow");
}
function shrink() {
let node = document.getElementById("item");
swap_animation(node, "grow", "shrink");
}
.grow {
animation-name: title-min;
animation-duration: 10s;
animation-timing-function: linear;
animation-fill-mode: forwards;
transform-origin: 0% 100% 0;
}
.shrink {
animation-name: title-min;
animation-duration: 10s;
animation-timing-function: linear;
animation-direction: reverse;
animation-fill-mode: forwards;
transform-origin: 0% 100% 0;
}
@keyframes title-min
{
from { transform: scale(0.5); }
to { transform: scale(1.0); }
}
<body>
<button onclick="grow()">Eat me! </button>
<button onclick="shrink()">Drink me! </button>
<h1 id="item">Alice </h1>
</body>
该示例显示,如果您在Eat me!和之间单击Drink me!,Alice 会在 10 秒内增长和缩小。但是,如果您在两者之间切换,您会注意到动画从切换前的位置继续播放。
我想我在某处读到,这样做的一种方法是克隆对象并用新对象替换旧对象。这似乎真的有点矫枉过正,我认为可能会导致性能问题,如果对象很大,更是如此,而且也会很糟糕,因为它会导致内存碎片。
必须有某种方法来保留对象并修改它的属性来解决这个问题,不是吗?
解决方案
好的,我找到了答案。这是触发回流。从这个网站得到了答案。不完全确定那里在void
做什么。
function swap_animation(node, from, to) {
node.classList.remove(from);
void node.offsetWidth;
node.classList.add(to);
}
function grow() {
let node = document.getElementById("item");
swap_animation(node, "shrink", "grow");
}
function shrink() {
let node = document.getElementById("item");
swap_animation(node, "grow", "shrink");
}
.grow {
animation-name: title-min;
animation-duration: 10s;
animation-timing-function: linear;
animation-fill-mode: forwards;
transform-origin: 0% 100% 0;
}
.shrink {
animation-name: title-min;
animation-duration: 10s;
animation-timing-function: linear;
animation-direction: reverse;
animation-fill-mode: forwards;
transform-origin: 0% 100% 0;
}
@keyframes title-min
{
from { transform: scale(0.5); }
to { transform: scale(1.0); }
}
<body>
<button onclick="grow()">Eat me! </button>
<button onclick="shrink()">Drink me! </button>
<h1 id="item">Alice </h1>
</body>
推荐阅读
- python - Python 错误:意外的表达式语法:将文件复制到文件夹脚本
- r - 使用 Leaflet 中的响应式日期输入创建地图的闪亮应用程序
- api - 是否有推荐的 VueJS 应用程序 API 和 Vuex 设计模式
- ios - iOS 14.4.2 似乎禁用了视频自动播放
- python - 如何将 Django Celery App 从 Elastic Beanstalk Amazon Linux 1 升级到 Amazon Linux 2
- css - 如何将图像设置为 div 容器顶部的背景图像
- go - select 语句在通道中究竟是如何工作的?
- jmeter - 如何使用 RSA 256 私钥在 JMETER 上生成 JWT 令牌所需的库或 jar 文件?
- android - 如何在不使用 webview 或浏览器的情况下实现 paypal?
- java - 子类方法具有较弱的访问说明符。但我可以覆盖。这怎么发生的?