Detail the use of the offsetleft attribute in javascript

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

This property returns the distance of the current element from the left edge of a parent element, which is also required.

(1). If there is a positioning element in the parent element, it returns the distance to the edge of the positioning element closest to the current element.
(2). If there is no positioning element in the parent element, the distance relative to the left edge of body will be returned.

Grammatical structure:

obj.offsetleft

Note: This property is read-only and cannot be assigned.

Code example:


<!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 the distance from the inner element to the left of the main element, because the main element is the first to locate the 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;
 margin:100px;
}
#box{
 width:200px;
 height:200px;
 background:blue;
 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 the size of the inner element to the left of the body element.

This property has a definite compatibility problem, as detailed in the offsetleft Compatibility Brief introduction section 1.

What exactly does the offsetLeft attribute in ps:js do?

You can determine the distance of an object to the left of document, which is the left edge of the browser. So if you write an div and you get this div then alert(your ES39en.offsetLeft) will see how far it is to the left of the browser. Of course you can also use it to assign objects, offset not only Left but offsetTop offsetWidth offsetHeight are very useful attributes in JS.


Related articles: