如何在元素上重复淡入效果



更新

添加延迟解决了我的问题:

setTimeout(() => price.classList.add("fade-it"), 100);

但这个答案对我来说也是有效的

原始问题

我对背景颜色有一个渐变效果,应该由我不时发起重复

我使用的是纯CSS:

<style>
@-webkit-keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
@-moz-keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
@keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
.fade-it {
-webkit-animation: yellow-fade 1s ease-in-out 0s;
-moz-animation: yellow-fade 1s ease-in-out 0s;
-o-animation: yellow-fade 1s ease-in-out 0s;
animation: yellow-fade 1s ease-in-out 0s;
}
</style>

在已经播放过一次之后,如何重新启动此效果?

我的代码在第一次之后就不起作用了:

var price = document.getElementById("price");
if (price.classList.contains("fade-it")) {
price.classList.remove("fade-it");
}
price.classList.add("fade-it");

您可以通过从DOM中删除节点然后将其添加回来来实现这一点。append函数正是这样做的,只需将元素附加到它的parentNode中即可。让元素自己的包装器成为parentNode,这样它就不会与其他同级元素一起重新排序。

const price = document.getElementById("price");
const btn = document.getElementById("fade-price");
const fade = function() {
if (price.classList.contains("fade-it")) {
price.classList.remove("fade-it");
}
price.classList.add("fade-it");
}
document.addEventListener("DOMContentLoaded", function() {
fade()
});
btn.addEventListener("click", function() {
price.parentElement.append(price)
});
@-webkit-keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
@-moz-keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
@keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
.fade-it {
-webkit-animation: yellow-fade 1s ease-in-out 0s;
-moz-animation: yellow-fade 1s ease-in-out 0s;
-o-animation: yellow-fade 1s ease-in-out 0s;
animation: yellow-fade 1s ease-in-out 0s;
}
<div>
<h4 id="price">$9.99</h4>
</div>
<button id="fade-price">
fade
</button>

最新更新