所以我这里有一个非常简单的例子,我通过 JS 应用动画来增长我的内部 div。然而,在尝试用 JS 反转动画时,我发现它没有过渡;相反,它会突然恢复到原始状态。
示例:
const grow = document.querySelector('.grow');
const reverse = document.querySelector('.reverse');
const inner = document.querySelector('.inner');
grow.addEventListener('click', function() {
inner.classList.add('grow');
})
//things I've tried
// reverse.addEventListener('click', function() {
// inner.classList.add('reverse');
// })
reverse.addEventListener('click', function() {
inner.style.animationDirection = 'reverse';
})
html, body {
height: 100%;
width: 100%;
margin: 0;
}
.container {
height: 100%;
width: 100%;
background: orange;
position: relative;
}
.inner {
position: absolute;
bottom: 0;
height: 52px;
width: 80%;
background: #fff;
}
.grow {
animation: grow forwards 1s ease-in-out;
}
.reverse {
animation: grow reverse 1s ease-in-out;
}
@keyframes grow {
from {
height: 52px;
}
to {
height: 100%;
}
}
<div class="container">
<div class="inner">
<button class="grow">Grow</button>
<button class="reverse">Reverse</button>
</div>
</div>
有人可以向我解释为什么会发生这种情况,以及如何在不添加标记为“收缩”的单独关键帧的情况下顺利恢复过渡吗?
最佳答案
这是因为 .grow
和.reverse
附于.inner
这让事情变得一团糟。您必须删除.grow
添加.reverse
之前。但是,这次当您删除.grow
时动画后,div 的高度将减小到 52px
再次强调,所以在申请之前必须保持其高度.reverse
。但是(再次),您需要减少 .inner
运行后高度.reverse
,否则它不会失去高度。所以你可以做这样的事情:
reverse.addEventListener('click', function() {
inner.classList.remove('grow');
inner.style.height = '100%';
// You need setTimeout() idk why
setTimeout(function() {
inner.classList.add('reverse');
inner.style.height = '52px';
}, 10);
})
关于javascript - 使用 Vanilla JS 反转动画的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53275793/