页面中的元素的offsetLeft : 离其最近的已经定位的元素
① 如果离其最近的元素没有定位,就相对于body元素计算
例如:
<style type="text/css">
.box1 {
width: 100px;
height: 100px;
background: red;
}
#box2 {
width: 50px;
height: 50px;
background: green;
margin: 0 auto;
}
</style>
<body>
<div class="box1">
<div id="box2"></div>
</div>
<script type="text/javascript">
var box2 = document.getElementById('box2');
alert(box2.offsetParent.tagName); //输出BODY
alert(box2.offsetLeft); //输出从33
</script>
</body>
id为box2的div元素的祖先元素中没有已经定位的元素,所以box2的offsetLeft是相对于body元素计算所得的。
② 离其最近的元素已经定位
例如:
<style type="text/css">
.box1 {
width: 100px;
height: 100px;
background: red;
position:relative; /* 这个是多加的 */
}
#box2 {
width: 50px;
height: 50px;
background: green;
margin: 0 auto;
}
</style>
<body>
<div class="box1">
<div id="box2"></div>
</div>
<script type="text/javascript">
var box2 = document.getElementById('box2');
alert(box2.offsetParent.tagName); //输出DIV
alert(box2.offsetLeft); //输出从25
</script>
</body>
offsetTop同理.