jquery method Position () differs from offset ()

Source: Internet
Author: User

Refer to others to write more clearly, the red part of the focus:

When using jquery to get the position of an element, we use the position () or offset () method, and two methods return an object with two properties-the left margin and the top margin, and two of them differ in the position relative to the point.

You can look at the diagram below:

We can generally see the difference between the two.

Position () Gets the distance relative to its nearest parent element with a relative position (position:relative), and returns the distance relative to the browser if no such element is found.

Offset () always returns the distance relative to the browser document, which ignores the outer element

Below is a simple example where the outer div element (position:relative) is only one:

<divID="outer"style="width:200px;position:relative; Left:100px;"><divID="inner"style="position:Absolute; Left:50px;Top:60px;"></div></div>
//Gets the location relative to the nearest parent (position:relative)varvposition= $("#inner").position();Alert(vposition. Left);//output:Alert(vposition.Top);//output:varVoffset= $("#inner").Offset();Alert(Voffset. Left);//Output: $ ("#outer"). Offset (). left+50Alert(Voffset.Top);//Output: $ ("#outer"). Offset (). top+60

In different browsers, offset () is different from the location of the browser, I believe you see the corresponding comments above, has mastered the position () and the offset () method difference.

Original: Http://www.jquery001.com/position ()-offset (). html

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.