我希望 DIV 显示一条确认消息,其中每次单击都会激活 css 效果“动画”或“淡出”。它在第一次点击时工作正常,但在随后的点击中不起作用。
function clientedetail() {
document.getElementById("guardadoC").innerHTML = "Guardado.";
document.getElementById("guardadoC").style.cssText = "animation: background-fade 3s;padding:5px;";
}
@keyframes background-fade {
0% {
background-color: green;
}
100% {
background-color: none;
}
}
<input type="button" onclick="clientedetail()"></input>
<div id="guardadoC"></div>
最佳答案
您可以添加一个 addEventListener('animationend', function() { ... });
来重置动画,以便您可以再次运行它。
将 CSS 保存在 CSS 文件中而不是将其作为 JavaScript 中的字符串编写也是一个好主意。现在,我们正在向元素添加一个类来执行我们想要的操作。
function clientedetail() {
var el = document.getElementById("guardadoC");
el.innerHTML = "Guardado.";
el.classList.add("animating");
//This function runs when the CSS animation is completed
var listener = el.addEventListener('animationend', function() {
el.classList.remove("animating");
//this removes the listener after it runs so that it doesn't get re-added every time the button is clicked
el.removeEventListener('animationend', listener);
});
}
@keyframes background-fade {
0% {
background-color: green;
}
100% {
background-color: none;
}
}
#guardadoC {
padding:5px;
}
#guardadoC.animating {
animation: background-fade 3s;
}
<button type="button" onclick="clientedetail()">click me</button>
<div id="guardadoC"></div>
关于javascript - 每次都使背景淡入 "onclick",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55346125/