1, offsetLeft 获取的是相对于父对象的左边距;
2, left 获取或设置相对于具有定位属性(position定义为relative)的父对象 的左边距;
下面看看一些例子
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#div1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div id="div1"></div>
<script type="text/javascript">
function getStyle(obj, attr) {
if (obj.currentStyle) {//IE
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj, null)[attr];
}
}
var oDiv = document.getElementById('div1');
console.log('getStyle("left") = ' + getStyle(oDiv, 'left'));
console.log('offsetLeft = ' + oDiv.offsetLeft);
</script>
</body>
</html>
结果:oDiv.style.left = 0px , oDiv.offsetLeft = 0
#div1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
border: 3px solid black;
}
结果:oDiv.style.left = 0px , oDiv.offsetLeft = 0
#div1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
border: 3px solid black;
padding: 14px;
}
结果:oDiv.style.left = 0px , oDiv.offsetLeft = 0
#div1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
border: 3px solid black;
padding: 14px;
margin-left: 24px;
}
结果:oDiv.style.left = 0px , oDiv.offsetLeft = 24
可见,offsetLeft是考虑到了margin-left了,因为margin-left,div确实在左边空出了24px的空间,但是style.left不管,style.left只看样式表中的left,其他的不管,就像前文中讲到的offsetWidth, offsetWidth不仅仅考虑到样式表中的width,更是考虑到padding和border,如下:
offsetWidth = width + padding + border;
#div1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
border: 3px solid black;
padding: 14px;
margin-left: 24px;
}
结果:oDiv.style.width = 100px , oDiv.offsetWidth = 134 (100+3+3+14+14)
可见style.left得到的是字符串,带单位,而offsetLeft得到的是数字;
写在CSS样式里的width等样式你直接用style.width是获取不到的,但是用offsetWidth可以;
style.left可读可写,但是offsetLeft可读不可写;