Recently used to offset this ghost, but there is no understanding of the place, so test it!!
Basic usage: After locating an object, use the
offsetleft \ offsetTop \ offsetwidth \ offsetheight
You can get the object's width, height, distance to the left, distance from the right, and the exact value of the distance.
Forget, the outside of the big box with the position:relative;
Made two, inside the gray block, a use of positioning, a use of margin;
By comparison,
Notice that the 2nd, 4, exactly the same, gets the left and top margins of the parent element.
function offset (elem) {
var obj={
Left:elem.offsetLeft,
Top:elem.offsetTop,
Width:elem.offsetWidth,
Height:elem.offsetHeight
}
return obj;
}
Then add something.
function offset (elem) {
var obj={
Left:elem.offsetLeft,
Top:elem.offsetTop,
Width:elem.offsetWidth,
Height:elem.offsetHeight
}
While (elem! = document.body) {
elem = elem.offsetparent;
Console.log (elem);
Obj.left + = Elem.offsetleft;
Obj.top + = elem.offsettop;
}
return obj;
}
When you look at the 2nd and 4 data, the left and top values increase, which is the result of adding the margin to the element.
Gets the left and top margins of the element's distance viewport
is the role of offsetparent.
Why??? I'll check, I don't know.
Summarize::
Use offset to first get the margin to the viewport, and when the element parent element has position positioning, gets the margin to the parent element.
If using elem = elem.offsetparent; The value to be obtained is the distance to the viewport.
Description of a bit, hehe hehe ... Excuse me!!! This ghost in the calculation of the position of the element is very useful, the value can be used directly, no units!!!
Using native JS offset for learning