本文介绍了什么会使offsetParent为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JavaScript中进行定位。我正在使用基于的累积位置函数为每个 offsetParent 总和 offsetTop 和 offsetLeft ,直到顶部节点。

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.

然而,我遇到了一个问题,我感兴趣的元素中没有 offsetParent in Firefox浏览器。在IE offsetParent 中存在,但 offsetTop 和 offsetLeft 全部和最多为0,所以它的效果与Firefox相同。

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.

什么会导致在屏幕上清晰可见和可用的元素没有 offsetParent ?或者,更实际一点,我如何才能找到这个元素的位置,以便在它下面放置一个下拉菜单?

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. 打开
  2. 在Web浏览器的控制台(例如Chromev21)中运行以下代码:

  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


为什么 offsetParent 该元素 null ?

Why is the offsetParent of that element null?

推荐答案

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

If the document hasn't finished loading then offsetParent can be null

这篇关于什么会使offsetParent为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!