Js gets the implementation code for the element's position relative to the window

  • 2020-03-30 04:03:31
  • OfStack

JS gets the offsetTop,offsetLeft and other attributes of the element

Obj. clientWidth // gets the width of the element

Obj. clientHeight // the height of the element
Obj. offsetLeft // element relative to the left of the parent element
Obj. offsetTop // the top of the element relative to the parent element
The width of the obj.offsetWidth // element
Obj. offsetHeight // the height of the element

The difference between:

ClientWidth = width + padding
ClientHeight = height + padding
OffsetWidth = width + padding + border
OffsetHeight = width + padding + border
Offset has more border width than client


//Gets the ordinate of the element (relative to the window)
function getTop(e){
  var offset=e.offsetTop;
  if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
  return offset;
}
//Gets the abscissa of the element (relative to the window)
function getLeft(e){
  var offset=e.offsetLeft;
  if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);
  return offset;
}

Before also wrote an article on the JS for acquiring element location: JS element offsetTop, offsetLeft properties, such as we can through the offsetTop and offsetLeft properties to obtain the position of the element relative to the window, but the offsetTop and offsetLeft properties are relative to the parent orientation, and often need to obtain position of the element is not in the outermost layer, so traverse the superior element offset related properties. Then efficiency is a problem.


//Gets the ordinate of the element (relative to the window)
function getTop(e){
var offset=e.offsetTop;
if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
return offset;
}
//Gets the abscissa of the element (relative to the window)
function getLeft(e){
var offset=e.offsetLeft;
if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);
return offset;
}

Chrome Firefox (Gecko) Internet Explorer Opera Safari
1.0 3.0 (1.9) 4.0 (Yes) 4.0

Note that bottom is the distance between the bottom of the element and the top of the window, not the distance between the bottom of position and the bottom of the window in CSS. 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.height

Original article, reproduced please note: reproduced from the front-end development


Related articles: