Transform doesnt animate when added class with transform: scale(1) via Jquery

天涯浪子 提交于 2021-01-27 22:43:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!