The jQuery.position of method gets a safe replacement method that does not have a value

  • 2020-05-16 06:15:15
  • OfStack

Calling the jQuery.position () method returns the position relative to the parent element, which is not the same as the.offset () method,.offset () returns the position relative to document, and.position () returns the position relative to the parent element, according to the official jQuery documentation.

But in fact, in the course of using it, we found that.position() often returns a value of 0. But it's not zero. Especially in the Google and IE browsers. Firefox does not have this problem.

Investigate its reason, based on Webkit browser (Google browser and Safari browsers), for example, only when the elements (such as pictures, flash) are completely loaded, the browser can access to the height and width of these elements, while firefox is in DOM after completion of loading can access these properties, it does not need to know the element of full size. The Google browser doesn't work. So in a browser like Google/IE, if you want to use. position () to get the offset of an element, you're going to get the initial value: 0.

One way to remedy this is to put your.position () call after the $(window).load () event, rather than after the $(document).ready event. But this approach is not necessarily reliable.

Another alternative is to use.offset() :


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, it is much more reliable and reassuring to use.


Related articles: