The Jquery.position () method gets a safe substitution method that does not have a value _jquery

Source: Internet
Author: User

The call to the Jquery.position () method returns the location relative to the parent element, as described in the jquery Official document, which is different from the. Offset () method. Offset () returns the position relative to the document, and. Position () Returns the position relative to the parent element.

But in fact, in the process of using, we found that. Position () returns a value that is often 0. But the fact is not 0. Especially Google browsers and IE browsers. Firefox does not have this problem.

The reason for this is based on WebKit browser (Google browser and Safari browser) For example, only when the elements (pictures, flash, etc.) fully loaded, the browser can access the height and width of these elements, and Firefox browser is completed after the completion of the DOM can access these properties, It does not need to know the full size of this element. And Google Browser can not. So in a browser like Google/ie, if you want to use. Position () to get the offset of an element, the value is usually the initial value: 0.

One way to remedy this is to put your. Position () call into the $ (window). After the load () event is triggered, not $ (document). After the Ready event. But this method is not necessarily reliable.

Another alternative is to use. Offset () to convert:

Copy Code code as follows:

JQuery.fn.aPosition = function () {
Thisleft = This.offset (). Left;
Thistop = This.offset (). Top;
Thisparent = This.parent ();

Parentleft = Thisparent.offset (). Left;
Parenttop = Thisparent.offset (). Top;

return {
Left:thisleft-parentleft,
Top:thistop-parenttop
};
};


Although this produces redundant code, but more reliable, with the people at ease.

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.