Javascript get element distance from top, bottom, left, and right of screen, with div(ul li)

Lionsure 2020-05-14 Original by the website

When you move to an element div (or ul li) in a web page, you often need to get the distance of the element div from the top, bottom, left, and right of the screen, so that you can know the position of element on the screen to control its movement.

Get the length or height of the element div, you can use javascript to get its width or height attributes, but the element has no attributes from the top, bottom, left and right of the screen. javascript has a method for getBoundingClientRect(). This method has four properties: top, bottom, left, and right. They are the distance from the top, bottom, left, and right of the screen, and you can get the distance of the div (ul li) from the top, bottom, left, and right of the screen.

 

Javascript get element distance from top, bottom, left and right

html:

<div id="divId" class="div">Javascript get element distance from top, bottom, left and right (How to get the distance (length) of div (ul li) from the top, bottom, left and right of the screen in Javascript)</div>

Css:

.div{ margin:80px 0px; position:relative; border:1px solid #787878; width:500px; height:30px; line-height:30px;}

 

Javascript code:

<script type="text/javascript">
       function GetElementDistance(obj) {
              var div = document.getElementById(obj);
              var topLen = div.getBoundingClientRect().top; // The distance (length) of div from the top of screen
              var bottomLen = div.getBoundingClientRect().bottom; // The distance (length) of div from the bottom of screen

              var leftLen = div.getBoundingClientRect().left; // The distance (length) of div from the left of screen
              var rightLen = div.getBoundingClientRect().right; // The distance (length) of div from the right of screen

       return "topLength=" + topLen + "; bottomLen=" + bottomLen + "; leftLen=" + leftLen + "; rightLen=" + rightLen;
       }
       document.write(GetElementDistance("divId"));
</script>

Output result: topLength=80; bottomLen=112; leftLen=8; rightLen=510

Because Css defines the position of a div as relative (position: relative), its position in the web page is different, and the output results are different.

The above example takes the distance from the top, bottom, left, and right of the screen to the div. The GetElementDistance method in javascript defines the required distance from the top, bottom, left, and right of the screen as parameters, so as long as the specific elements are passed to it, the distance from the top, bottom, left, and right sides of the screen can be got. The distance of ul li from the top, bottom, left, and right of the screen can be got by simply passing the corresponding id to the GetElementDistance method.