Using native JS offset for learning

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.