javascript——DOM之获取元素的位置
CSS部分:
div {padding: 40px 50px;}
#div1 {background: red;position: relative;}
#div2 {background: green; position: relative;}
#div3 {background: orange; position: relative;}
HTML部分:
<div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div>
JS部分:
window.onload = function() { var oDiv3 = document.getElementById('div3'); //alert(oDiv3.offsetLeft); //50 /* var iTop = 0; var obj = oDiv3; while(obj){ alert(obj.id + ':' + obj.offsetTop); //div3:40->div2:40->div1:8->body1:0 iTop += obj.offsetTop; //0->40->80->88->88 alert(iTop); //40->80->88->88 obj = obj.offsetParent; //div3->div2->div1->body1 alert(obj.id); //div2->div1->body1 } alert( iTop );*/ //alert( document.body.offsetTop ); //把获取位置封装成一个函数 function getPos(obj){ var pos = {left:0, top:0}; while(obj){ pos.left += obj.offsetLeft; pos.top += obj.offsetTop; obj = obj.offsetParent; } return pos; } var p = getPos(oDiv3); alert(p.top); alert(p.left); }