Javascript 更改 div 的位置并在应用动画后

Javascript Change position of a div and after apply an animation

我在页面中间有一个div。
我想改变我的 div 在父元素右上角的位置(没有动画),然后用动画移动到父元素的左上角。
所以,我第一次使用这段代码:
但这不能正常工作。

function doAnimation(){
  var child = document.getElementById("child");
  var parent = document.getElementById("parent");
  
  child.style.left = parent.offsetWidth + "px";
  child.classList.add("child-animation");
  child.style.left = 0 + "px";
}
#parent{
  position: relative;
  width: 500px;
  height: 200px;
  background-color: red;
}

#child{
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0;
  left: 225px;
  background-color: yellow;
}

#button{
  position: absolute;
  width: 100%;
  height: 30px;
  bottom: 0;
  background-color: grey;
}
  

.child-animation{
    -webkit-transition: all 700ms cubic-bezier(1,.01,.96,.87);
 -moz-transition: all 700ms cubic-bezier(1,.01,.96,.87);
 -ms-transition: all 700ms cubic-bezier(1,.01,.96,.87);
 -o-transition: all 700ms cubic-bezier(1,.01,.96,.87);
 transition: all 700ms cubic-bezier(1,.01,.96,.87);
}
<div id="parent">
  <div id="child">
  </div>
  <div id="button" onclick="doAnimation();">
  </div>
</div>

在我这样做之后:

这项工作呢?

function doAnimation () {
  var child = document.getElementById("child");
  var parent = document.getElementById("parent");
  
  child.style.left = parent.offsetWidth + "px";
  setTimeout( function () {
      child.classList.add("child-animation");
      child.style.left = 0 + "px";
   }, 0);
}
#parent{
  position: relative;
  width: 500px;
  height: 200px;
  background-color: red;
}

#child{
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0;
  left: 225px;
  background-color: yellow;
}

#button{
  position: absolute;
  width: 100%;
  height: 30px;
  bottom: 0;
  background-color: grey;
}
  

.child-animation{
    -webkit-transition: all 700ms cubic-bezier(1,.01,.96,.87);
 -moz-transition: all 700ms cubic-bezier(1,.01,.96,.87);
 -ms-transition: all 700ms cubic-bezier(1,.01,.96,.87);
 -o-transition: all 700ms cubic-bezier(1,.01,.96,.87);
 transition: all 700ms cubic-bezier(1,.01,.96,.87);
}
<div id="parent">
  <div id="child">
  </div>
  <div id="button" onclick="doAnimation();">
  </div>
</div>


我的问题是,为什么第一个代码不起作用而第二个 setTimeout(function,0) 有效?

请帮帮我!

需要强制重绘

您需要阅读 属性 让浏览器重新计算元素。像这样:

child.style.left = parent.offsetWidth + "px";
var forced=child.scrollLeft; // Forces a redraw
child.classList.add("child-animation");
child.style.left = 0 + "px";

这是由于浏览器如何将 属性 更改分组并在下一次重绘事件期间将它们一次性 运行 。第一种情况:

child.style.left = parent.offsetWidth + "px";
child.classList.add("child-animation");
child.style.left = 0 + "px";

基本上同时 运行s,这意味着浏览器的行为就像它实际上只收到了这个:

child.classList.add("child-animation");
child.style.left = 0 + "px";

并非所有浏览器都像这样批处理(分组)属性,因此这就是它因浏览器而异的原因。