For the basic usage of this attribute, please refer to the chapter Detailed explanation of the usage of offsetleft attribute .
This attribute has certain compatibility issues, that is, in IE7 browser, its return value is the distance to the left of the nearest parent element.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>蚂蚁部落</title> <style type="text/css"> * { margin: 0px; padding: 0px; } #main { width: 300px; height: 300px; background: red; position: absolute; left: 100px; top: 100px; } #box { width: 200px; height: 200px; background: blue; margin:50px; overflow:hidden; } #inner { width: 50px; height: 50px; background: green; text-align: center; line-height: 50px; margin: 50px; } </style> <script type="text/javascript"> window.onload=function(){ var inner=document.getElementById("inner"); inner.innerHTML=inner.offsetLeft; } </script> </head> <body> <div id="main"> <div id="box"> <div id="inner"></div> </div> </div> </body> </html>
The above code returns a value of 100 in other browsers, but the return value in IE7 is 50.
As for IE6, there is no test. If you are interested, you can do a test.
Let me take some time to introduce to you the difference between offsetLeft and style.left
offsetLeft gets the left margin relative to the parent object
left gets or sets the left margin
relative to the parent object with positioning attribute (position is defined as relative)If the position of the parent div is defined as relative and the position of the child div is defined as absolute, then the value of style.left of the child div is relative to the value of the parent div,
This is the same as offsetLeft, the difference is:
1. style.left returns a string, such as 28px, and offsetLeft returns a value of 28. If you need to calculate the obtained value,
It is more convenient to use offsetLeft.
2. style.left is read-write, offsetLeft is read-only, so to change the position of the div, you can only modify style.left.
3. The value of style.left needs to be defined in advance, otherwise the value obtained will be empty. And it must be defined in html. I have done experiments. If it is defined in
In css, the value of style.left is still empty. This is the problem I encountered at the beginning. I can't always get the value of style.left.
offsetLeft can still be obtained without defining the position of the div in advance.