什么会使offsetParent null?

Bri*_*say 13 html javascript positioning

我试图在JavaScript中进行定位.我正在使用基于经典quirksmode函数的累积位置函数,该函数对每个函数求和offsetTop,直到顶部节点.offsetLeftoffsetParent

但是,我遇到了一个问题,我感兴趣的元素offsetParent在Firefox 中没有.在IE中offsetParent存在,但是offsetTop并且offsetLeft总计为0,因此它与Firefox中的效果相同.

什么会导致在屏幕上清晰可见和可用的元素没有offsetParent?或者,更实际的是,我如何找到该元素的位置以便在其下方放置下拉?

编辑:这是如何重现这个特定的一个实例(没有通过当前接受的答案解决):

  1. 打开Stack Overflow主页.
  2. 在Web浏览器的控制台中运行以下代码(例如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
    
    Run Code Online (Sandbox Code Playgroud)

为什么offsetParent那个元素null

Phr*_*ogz 41

我已经作出的2304点的div的测试与值的唯一组合position,display以及visibility,嵌套在每一个那些值的独特的组合,并确定:

在以下情况下
,作为后代的其他有效元素<body>
将不具有offsetParent值:

  • 元素有position:fixed(Webkit和IE9)
  • 元素有display:none (Webkit和FF)
  • 任何祖先都有display:none (Webkit和FF)

期望没有父元素或者没有添加到页面本身的元素(不是页面的后代<body>)的元素也是合理的offsetParent==null.


Gre*_*reg 15

如果文档尚未完成加载,则offsetParent可以为null


Iva*_*van 13

https://developer.mozilla.org/en/DOM/element.offsetParent

当element.display设置为"none"时,offsetParent返回null.

  • 根据我在下面的回答,我现在已经编辑了MDN页面,注意非FF浏览器还有其他情况也会导致这种情况. (2认同)