
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.onclick=function(){
oDiv3.style.left=-(oDiv3.getBoundingClientRect().left-parseInt(oDiv3.offsetLeft))+"px";
}
