Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

javascript - What would make offsetParent null?

I am trying to do positioning in JavaScript. I am using a cumulative position function based on the classic quirksmode function that sums offsetTop and offsetLeft for each offsetParent until the top node.

However, I am running into an issue where the element I'm interested in has no offsetParent in Firefox. In IE offsetParent exists, but offsetTop and offsetLeft all sum up to 0, so it has the same problem in effect as in Firefox.

What would cause an element that is clearly visible and usable on the screen to not have an offsetParent? Or, more practically, how can I find the position of this element in order to place a drop-down beneath it?

Edit: Here's how to reproduce one particular instance of this (not solved by the currently-accepted answer):

  1. Open the home page of Stack Overflow.
  2. Run the following code in the Console of the web browser (e.g. Chromev21):

    var e = document.querySelector('div');
    console.log(e);
    // <div id="notify-container"></div>
    do{
      var s = getComputedStyle(e);
      console.log(e.tagName,s.display,s.visibility,s.position,e.offsetParent);
    } while(e=e.parentElement)
    // DIV block visible fixed null
    // BODY block visible static null
    // HTML block visible static null
    

Why is the offsetParent of that element null?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have made a test of 2,304 divs with unique combinations of values for position, display, and visibility, nested inside unique combinations of each of those values, and determined that:

an otherwise-valid element
that is a descendant of <body>
will not have an offsetParent value if:

  • The element has position:fixed (Webkit and IE9)
  • The element has display:none (Webkit and FF)
  • Any ancestor has display:none (Webkit and FF)

It is also reasonable to expect that an element that has no parent, or that is not added to the page itself (is not a descendant of the <body> of the page), will also have offsetParent==null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...