【发布时间】:2022-02-06 10:10:06
【问题描述】:
我有一个起初不可见的元素 (opacity: 0)。
当一个动画被触发时,它会淡入,但由于opacity 的值似乎被重置了,它在完成后又消失了。
如何防止重置动画属性?
我在 Google Chrome 中使用 animate.css 4.1.1。
示例上下文:
HTML:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
<div class="main-container">
<div id="test1"></div>
</div>
CSS:
#test1 {
position: absolute;
margin: 10%;
width: 25%;
height: 25%;
opacity: 0;
background: blue;
}
下面的代码使用这个JS函数来添加动画类(在animate.css website找到):
const animateCSS = (element, animation, prefix = 'animate__') =>
// We create a Promise and return it
new Promise((resolve, reject) => {
const animationName = `${prefix}${animation}`;
const node = document.querySelector(element);
node.classList.add(`${prefix}animated`, animationName);
// When the animation ends, we clean the classes and resolve the Promise
function handleAnimationEnd(event) {
event.stopPropagation();
node.classList.remove(`${prefix}animated`, animationName);
resolve('Animation ended');
}
node.addEventListener('animationend', handleAnimationEnd, {once: true});
});
这里我尝试触发一个 in 动画,稍等片刻,然后有一个 out 动画。
所描述的问题表现为闪烁(可以在此jsfiddle 中看到。)
-
首先我认为解决方案应该像更改属性一样简单。
完成后:
let test1 = document.getElementById("test1"); animateCSS("#test1", "flipInX") // flickers .then(()=>{ test1.style.opacity = 1; }); ... animateCSS("#test1", "flipOutX") .then(()=>{ test1.style.opacity = 0; });马上:
let test1 = document.getElementById("test1"); animateCSS("#test1", "flipInX") test1.style.opacity = 1; ... animateCSS("#test1", "flipOutX") // flickers test1.style.opacity = 0;
-
然后我认为闪烁是由任何动画延迟引起的。
所以我禁用了它:test1.style.setProperty('--animate-delay', '0s');` document.documentElement.style.setProperty('--animate-delay', '0s');没有任何影响。
我做错了什么?
更新:
我最终使用了答案的修改版本:
function animateCss(node, animationName, duration = 1, prefix = 'animate__') {
const envCls = `${prefix}animated`;
const animationCls = `${prefix}${animationName}`;
// Remove all applied animate.css classes.
node.className = node.className
.split(" ")
.filter((cls) => !cls.startsWith(prefix))
.join(" ");
// Promise resolves when animation has ended.
return new Promise((resolve, reject) => {
node.addEventListener('animationend', (event) => {
event.stopPropagation();
resolve('Animation ended');
}, {once: true});
node.style.setProperty('--animate-duration', `${duration}s`);
node.classList.add(envCls, animationCls); // Starts CSS animation.
});
}
// --- Test ---
let test1 = document.getElementById("test1");
// hide the element at first.
animateCss(test1, "fadeOut", 0);
setTimeout(()=>{
animateCss(test1, "flipInX");
}, 1000);
setTimeout(()=>{
animateCss(test1, "zoomOut");
}, 5000);
【问题讨论】:
-
This question 类似,但没有真正的答案。
-
this question 的答案对我也不起作用。
标签: javascript animation flicker animate.css