JS gets the offsetTop, offsetLeft and other properties of the element
obj.clientWidth //Get the width of the element
obj.clientHeight //The height of the element
obj.offsetLeft //The element relative to the parent element's left
obj.offsetTop //The top of the element relative to the parent element
obj.offsetWidth //The width of the element
obj.offsetHeight //The height of the element
the difference:
clientWidth = width + padding
clientHeight = height + padding
offsetWidth = width + padding + border
offsetHeight = width + padding + border
offset has more border width than client
//Get the horizontal coordinate of the element (relative to the window) function getTop(e){ var offset=e.offsetTop; if(e.offsetParent!=null) offset+=getTop(e.offsetParent); return offset;}//Get the horizontal coordinate of the element (relative to the window) function getLeft(e){ var offset=e.offsetLeft; if(e.offsetParent!=null) offset+=getLeft(e.offsetParent); return offset;}I have also written a JS article about getting element locations: JS obtains the element's offsetTop, offsetLeft and other attributes. We can obtain the element's position relative to the window through the offsetTop and offsetLeft attributes, but the offsetTop and offsetLeft attributes are both positioned relative to the parent element, and the elements that usually need to obtain the position are not at the outermost layer, so offset-related attributes that traverse the upper element are indispensable. Then efficiency becomes a problem.
//Get the horizontal coordinate of the element (relative to the window) function getTop(e){var offset=e.offsetTop;if(e.offsetParent!=null) offset+=getTop(e.offsetParent);return offset;}//Get the horizontal coordinate of the element (relative to the window) function getLeft(e){var offset=e.offsetLeft;if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);return offset;}Fortunately, the browser provided me with the corresponding interface getBoundingClientRect. This method first appeared in the IE browser. Later browsers also supported this method, and it was more perfect. In IE, they can only get the left, top, bottom, and right attributes of elements, and the later modern browsers can also get the width and width of elements.
| Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|
| 1.0 | 3.0 (1.9) | 4.0 | (Yes) | 4.0 |
It should be noted here that bottom is the distance between the bottom of the element and the top of the window, rather than the bottom of the position in css relative to the bottom of the window. Similarly, the rihgt attribute is the distance between the rightmost element and the left side of the window.
var box = document.getElementById("box");var pos = box.getBoundingClientRect();box.innerHTML = "top:"+pos.top + "left:"+pos.left + "bottom:"+pos.bottom + "right:"+pos.right + "width:"+pos.width + "height:"+pos.heightOriginal articles, please indicate the reprint: Reprinted from front-end development