HTML
<input type="button" name="" id="" value="点击运动" />
<div id="div1">
<div id="div2">
<div id="div3"></div>
</div>
</div>
CSS
#div1,#div1 div{
position: absolute;
top: 10px;
}
#div1{
width: 100px;
height: 100px;
background: red;
left: 100px;
border: 2px solid #000;
top: 100px;
}
#div2{
width: 60px;
height: 60px;
background: blue;
left: 30px;
border: 2px solid #fff;
}
#div3{
width: 30px;
height: 30px;
background: yellow;
left: 20px;
border: 2px solid orange;
transition: 1s left;
}
JS
/*
DOM节点
* node.offsetParent最近的有定位属性的祖先节点
* 如果祖先节点都没有定位,那么默认为body
*
* node.offsetLeft/node.offsetTop 最近的有定位属性的祖先节点的距离
*
* node.offsetLeft左外边框到定位父级的左内边框的距离
* node.offsetTop上外边框到定位父级的上内边框的距离
*
*
* node.getBoundingClientRect()
* node.getBoundingClientRect().left
* 获取元素的盒模型信息
* 返回值为一个对象
* left top bottom right width height
* 相对于浏览器可视区域
* 注意:获取的值会根据滚动条滚动的距离变换的
*
*
*
*
* */
//点击按钮,div3运动到窗口边上
var oBtn=document.getElementsByTagName("input")[0];
var oDiv3=document.getElementById("div3");
oBtn.οnclick=function(){
oDiv3.style.left=-(oDiv3.getBoundingClientRect().left-parseInt(oDiv3.offsetLeft))+"px";
}