记录js控制动画无效的BUG
js控制css动画无效的bug
错误代码是这样的
const animationDiv = document.getElementsByClassName("animationStyle")[0]; //动画div
const animationButton = document.getElementById("animation"); // 按钮
animationButton.addEventListener("click", () => {
console.log(111, animationDiv.style.animation);
if (animationDiv.style.animation =="" || "0s ease 0s 1 normal none running none") {
console.log(222);
animationDiv.style.animation = "xuanzhuan 5s linear infinite";
} else {
animationDiv.style.animation = "none";
console.log(333);
}
});
原因
原因在于你设置样式后,虽然动画运行了,但是再获取样式的时候还空(“”),所以还会走进打印222的地方。
解决方法就是 去除“”的内容,改为 "0s ease 0s 1 normal none running none"
就好了
修改后代码
const animationButton = document.getElementById("animation"); // 按钮
animationButton.addEventListener("click", () => {
console.log(111, animationDiv.style.animation);
if (animationDiv.style.animation =="0s ease 0s 1 normal none running none") {
console.log(222);
animationDiv.style.animation = "xuanzhuan 5s linear infinite";
} else {
animationDiv.style.animation = "none";
console.log(333);
}
});