为什么可以't我重用CSS关键帧动画

Why can't I reuse a CSS keyframe animation?

本文关键字:CSS 关键帧 动画 为什么      更新时间:2023-09-26

我想每次提交一个CSS关键帧动画,但目前它只适用于第一次。你能看出我做错了什么吗?

CSS:

@keyframes enlarge {
0%   {-webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1);}
100% {-webkit-transform: scale(1.5); -ms-transform: scale(1.5); transform: scale(1.5);}
}
.enlarge {
animation-name: enlarge;
animation-duration: 2s;

JS:

var enlarge = function(response) {
    document.querySelector("#messageContainer").classList.add("enlarge");
    var reset = setTimeout(function() {
        document.querySelector("#messageContainer").classList.remove("enlarge");
    }, 2000);
};

在写这篇文章的时候,我有点期待解决方案会出现,但事实并非如此。

根据您的描述,您的代码似乎可以按预期工作。。。尝试点击下面的"运行代码段":

var enlarge = function(response) {
    document.querySelector("#container").classList.remove("hidden");
    document.querySelector("#example").classList.add("enlarge");
    var reset = setTimeout(function() {
        document.querySelector("#example").classList.remove("enlarge");
        document.querySelector("#container").classList.add("hidden");
    }, 2000);
};
#example { 
  background: red;
  width: 150px;
}
@keyframes enlarge {
0%   {-webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1);}
100% {-webkit-transform: scale(1.5); -ms-transform: scale(1.5); transform: scale(1.5);}
}
.hidden { display: none; }
.enlarge {
    animation-name: enlarge;
    animation-duration: 2s;
}
<div id="container" class="hidden">
    <div id="example">My example text</div>
</div>
<button onclick="enlarge()">Submit</button>

你确定你的放大功能在每次点击提交按钮时都在运行吗?

根据您的enlarge()函数接受一个"response"参数的事实判断,我假设您在AJAX请求的响应处理程序中使用了它——如果表单已经提交过一次,这个AJAX请求会返回一个不成功的错误代码吗?如果这个函数被附加到onSuccess()方法,这将解释为什么它只播放一次动画;只有在第一次点击按钮时,请求才会"成功"。