问题
I am trying to insert a new div with fancy transform: scale() animation when button is clicked, however it doesn't animate. I am not sure why. Any suggestions? Thanks.
$("button").click(event => {
let div = $("<div></div>");
div.insertAfter("button");
div.addClass("animate");
});
div{
height: 50px;
width: 50px;
background: #000;
transform: scale(0);
transition: transform 1s;
}
.animate{
transform: scale(1);
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<button>Button</button>
回答1:
You need to break up the adding the div
and adding a class to it, e.g. using a setTimeout().
W/o the above, the animation won't apply the transition, as it does all in one go.
Stack snippet
$("button").click(event => {
let div = $("<div></div>");
div.insertAfter("button");
setTimeout(function() {
div.addClass("animate");
}, 10)
});
div{
height: 50px;
width: 50px;
background: #000;
transform: scale(0);
transition: transform 1s;
}
.animate{
transform: scale(1);
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<button>Button</button>
If you use animation
on the other hand, it will work
Stack snippet
$("button").click(event => {
let div = $("<div></div>");
div.insertAfter("button");
div.addClass("animate");
});
div{
height: 50px;
width: 50px;
background: #000;
transform: scale(0);
}
.animate{
animation: scale 1s forwards;
}
@keyframes scale {
from { transform: scale(0); }
to { transform: scale(1); }
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<button>Button</button>
回答2:
how it seems to me that it's better to use @keyframes
and you don't need to use addClass
$("button").click(event => {
let div = $("<div></div>");
div.insertAfter("button");
});
div{
height: 50px;
width: 50px;
background: #000;
animation: scale 1s forwards;
}
@keyframes scale {
from { transform: scale(0); }
to { transform: scale(1); }
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<button>Button</button>
来源:https://stackoverflow.com/questions/51248926/transform-doesnt-animate-when-added-class-with-transform-scale1-via-jquery