The getBoundingClientRect method gets the relative position of the element on the page

To get the element position, you can use offset or getBoundingClientRect. It is troublesome to use offset because of poor compatibility, and the offset to get the position will form a "backtracking". The getBoundingClientRect method has
better compatibility, basically all browsers support it, and it is easier and simpler to use.

1. Use the syntax:

element.getBoundingClientRect();

There are no parameters in the method, and the return value is an object type.

 

2. In IE8 and below browsers, the attribute values ​​contained in the return value object are:

top: The distance between the top edge of the element and the top of the document;

right:  the distance between the right edge of the element and the left side of the document;

bottom: the distance between the bottom edge of the element and the top of the document;

left: the distance between the left edge of the element and the left side of the document;

 

3. In browsers such as IE9 and above, Google, Firefox, etc., the attribute values ​​contained in the return value object are:

top: the distance between the top edge of the element and the top of the document;

right: the distance between the right edge of the element and the left side of the document;

bottom: the distance between the bottom edge of the element and the top of the document;

left: the distance between the left edge of the element and the left side of the document;

width: the width of the element (including padding and border)

height: the height of the element (including padding and border)

 

4. There is no solution for width and height attributes in IE8 and below browsers:

In IE8 and below browsers, the width and height of an element can be calculated by:

Such as:

var dom = document.querySelector("#demo"),
r = dom.getBoundingClientRect();

var width = r.right - r.left;
var height = r.bottom - r.top;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324842138&siteId=291194637