JS gets the offsetTop, offsetLeft and other attributes of the element
obj.clientWidth //Get the width of the element
obj.clientHeight //The height of the element
obj.offsetLeft //The left
of the element relative to the parent element
obj.offsetTop //The top
of the element relative to the parent element
obj.offsetWidth //Width of element
obj.offsetHeight //Height of element
Difference:
clientWidth = width padding
clientHeight = height padding
offsetWidth = width padding border
offsetHeight = width padding border
The offset is more than the width of the border
//获取元素的纵坐标(相对于窗口) function getTop(e){ var offset=e.offsetTop; if(e.offsetParent!=null) offset+=getTop(e.offsetParent); return offset; } //获取元素的横坐标(相对于窗口) function getLeft(e){ var offset=e.offsetLeft; if(e.offsetParent!=null) offset+=getLeft(e.offsetParent); return offset; }
I have also written an article about getting the position of elements in JS before: JS gets the offsetTop, offsetLeft and other attributes of the element. We can get the position of the element relative to the window through the offsetTop and offsetLeft attributes, but the offsetTop and offsetLeft attributes are relative to The parent element is positioned, and usually the elements that need to obtain the position are not in the outermost layer, so it is indispensable to traverse the offset-related attributes of the superior element. Then efficiency becomes a problem.
//获取元素的纵坐标(相对于窗口) function getTop(e){ var offset=e.offsetTop; if(e.offsetParent!=null) offset+=getTop(e.offsetParent); return offset; } //获取元素的横坐标(相对于窗口) 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 IE browser, and later browsers also supported this method, and it is more complete. IE can only get the element attributes of left, top, bottom, and right, and later modern browsers can also obtain the width and
of the element.
Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|
1.0 | 3.0 (1.9) | 4.0 | (Yes) | 4.0 |
What should be noted here is that bottom is the distance between the bottom of the element and the top of the window, not the bottom of the position in CSS relative to the bottom of the window. Similarly, the rihgt attribute is the distance between the rightmost part of the 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.height
Original article, please indicate when reprinting: Reprinted from front-end development