示例代码:
<style>
div {padding: 40px 50px;}
#div1 {background: red;}
#div2 {background: green; /* position: relative; */}
#div3 {background: orange; /* position: relative; */}
</style>
<script>
window.onload = function() {
var oDiv3 = document.getElementById('div3');
}
</script>
</head>
<body id="body1">
<div id="div1">
<div id="div2">
<div id="div3"></div>
</div>
</div>
</body>
元素.offsetLeft[Top] : 只读 属性 当前元素到定位父级的距离(偏移值)
到当前元素的offsetParent的距离
如果没有定位父级
offsetParent -> body
offsetLeft -> html
alert( oDiv3.offsetParent );
alert( oDiv3.offsetLeft );
如果有定位父级
ie7以下:如果自己没有定位,那么offsetLeft[Top]是到body的距离
alert( oDiv3.offsetLeft );
如果自己有定位,那么就是到定位父级的距离
#div2 {background: green; position: relative;}
alert( oDiv3.offsetLeft );
其他:到定位父级的距离
style.width : 样式宽
clientWidth : 可视区宽(width + padding)
offsetWidth : 占位宽(width + padding + border)
示例代码:
<script>
window.onload = function() {
var oDiv = document.getElementById('div1');
alert( oDiv.style.width ); //100
alert( oDiv.clientWidth ); //样式宽 + padding 120
alert( oDiv.offsetWidth ); //样式宽 + padding + border 可视区宽 + 边框 122
}
</script>
</head>
<body>
<div id="div1" style="width: 100px; height: 100px; border: 1px solid red; padding: 10px; margin: 10px;"></div>
</body>