Talk about the understanding of offsetleft compatibility

  • 2020-10-23 19:59:30
  • OfStack

For basic usage of this attribute, see offsetleft Attribute usage Details section 1.

This property has a 1-point compatibility problem, 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> The ant tribe </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 50 in IE7.

As for IE6, there is no test, those interested can do 1 test.

Let me give you a little space for the difference between offsetLeft and ES15en.ES16en

offsetLeft gets the left margin relative to the parent object

left gets or sets the left margin relative to the parent object that has the location attribute (position is defined as relative)

If position of the parent div is defined as relative and position of the child div is defined as absolute, then the value of style. left of the child div is the value relative to the parent div,
This is the same as offsetLeft except that:

style.left returns a string, such as 28px, and offsetLeft returns a value of 28. If you need to calculate the value obtained,
offsetLeft is more convenient.

2. style.left is read-write and offsetLeft is read-only, so to change the position of div, only style.left can be modified.

3. The value of style. left needs to be defined in advance, otherwise the value retrieved is empty. And it has to be defined in html, and I did an experiment with that
In css, the value of ES62en.left is still empty, which is the problem I had at the beginning, I always failed to get the value of ES64en.left.

offsetLeft is still reachable without defining the location of div in advance.


Related articles: