Home > Web Front-end > JS Tutorial > body text

Safe replacement method for jQuery.position() method that cannot obtain the value_jquery

WBOY
Release: 2016-05-16 16:09:56
Original
1284 people have browsed it

Calling the jQuery.position() method will return the position relative to the parent element. The jQuery official documentation describes that it is different from the .offset() method. .offset() returns the position relative to the document, while .position() returns the position relative to the parent element.

But in fact, during use, we found that the value returned by .position() is often 0. But the fact is not 0. Especially in Google Chrome and IE browser. Firefox doesn't have this problem.

The reason is that taking Webkit-based browsers (Google Chrome and Safari browser) as an example, only when elements (images, flash, etc.) are fully loaded, the browser can access the height and width of these elements. Firefox can access these properties after the DOM is loaded, and it does not need to know the full size of the element. Not so with Google Chrome. Therefore, in browsers such as Google/IE, if you want to use .position() to get the offset of an element, the value you get is often the initial value: 0.

One remedy is to place your .position() call after the $(window).load() event fires, rather than after the $(document).ready event. But this method may not be reliable.

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

Copy code The code is 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 generates redundant code, it is much more reliable and reassuring to use.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!