我在页面中间有一个div。
我想改变我的 div 在父元素右上角的位置(没有动画),然后用动画 move 到父元素的左上角。
所以,我第一次使用这段代码:
但这不能正常工作。
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";
所有这些本质上都是同时运行的,这意味着浏览器的行为就像它实际上只收到了这个:
child.classList.add("child-animation");
child.style.left = 0 + "px";
并非所有浏览器都像这样批处理(分组)属性,因此这就是它因浏览器而异的原因。
关于Javascript更改div的位置并在应用动画后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40794214/