offsetLeft, oDiv.style.left, getComputedStyle()
- offsetTop 当前元素到上级元素顶部的距离,返回无单位
- offsetLeft 当前元素到上级元素左侧的距离,返回无单位 left+外边距
- offsetWidth 当前元素的宽度,返回无单位 元素宽度+内边距+边框宽度
- offsetHeight 当前元素的高度,返回无单位
- .style.left 返回元素的左部位置,返回有单位 “px”
- getComputedStyle() 可以访问指定元素的指定CSS样式,返回有单位 “px”,格式:
1 getComputedStyle(需要访问样式属性的元素).样式属性
如果使用 getComputedStyle() 访问元素的 left,会出现测算错误,原因:若测量的元素有外边距, getComputedStyle() 测量 left 时不会考虑外边距。
<style type="text/css">
*{
margin: 0;
padding: 0;
background-color: lightblue;
}
div{
width: 100px;
height: 50px;
background: orange;
position: absolute;
top: 100px;
margin: 20px; //外边距
padding: 30px; //内边距
border: 5px dashed red; //边框
}
</style>
<div style="left: 120px;">
<img src="01.jpg" width="40px">
</div>
<script type="text/javascript">
let oDiv=document.getElementsByTagName('div')[0];
// alert(oDiv.offsetHeight);
// alert(oDiv.offsetWidth); //元素宽度+内边距+边框宽度
// alert(oDiv.offsetTop);
// alert(oDiv.offsetLeft); //当元素设置了外边距,则加上外边距
// alert(oDiv.style.left);
// alert(getComputedStyle(oDiv).left); //当元素设置了外边距,不加上外边距
</script>

浙公网安备 33010602011771号