【发布时间】:2016-11-24 20:40:22
【问题描述】:
我在页面中间有一个 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) 的第二个代码起作用?
请帮帮我!
【问题讨论】:
-
两者都适合我(Firefox)。哪个浏览器 - Chrome?编辑:是的;在 Firefox 中相同,在 Chrome 中不同。
标签: javascript html css animation move