CSS z-index 不起作用(使用相对定位,使用顶部和左侧)

CSS z-index Not Functioning (relative positioning used, top and left used)

我有以下代码使 'b' (div) 超越 'More text' (文本节点):

JavaScript、HTML 和输出:

function InsertDetails() {

  document.getElementById("UI-Slide-Content").focus();
  var HTMLToInsert = "div";

  var sel, range, html;
  var text = HTMLToInsert;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();

      range.insertNode(document.createTextNode("More text"));

      var b = document.createElement("div");
      b.style.zIndex = "2";
      b.style.position = "relative";
      b.style.backgroundColor = "lightGray";
      b.appendChild(document.createTextNode("Details"));
      b.style.padding = "5px";
      range.insertNode(b);

      var a = document.createElement(text);

      a.setAttribute("onclick", "DetailsSwitch(this);");

      a.style.backgroundColor = "buttonFace";
      a.innerHTML = "▼ Summary";
      a.style.padding = "5px";
      range.insertNode(a);
    }
  } else if (document.selection && document.selection.createRange) {
    //MessageBox("Feature Not Supported", "This feature does not work in Internet Explorer.");
  }

}

function DetailsSwitch(a) {
  var allDivs = document.getElementsByTagName("div");
  var c = 0;
  var d = a;
  var e = null;

  while (c < allDivs.length) {
    if (allDivs[c] == d) {
      e = allDivs[c + 1];
    }
    c++;
  }

  if (e.style.display == "block") {
    e.style.display = "none";
    d.innerHTML = d.innerHTML.replace("▼&nbsp;", "▶&nbsp;");
  } else {
    e.style.display = "block";
    d.innerHTML = d.innerHTML.replace("▶&nbsp;", "▼&nbsp;");
  }
}
<div id="UI-Slide-Content" contenteditable style="border: 1px solid black; width: 100%; height: 100%;">UI-Slide-Content</div>
<button onclick="InsertDetails();">Insert Details Pane</button>

尝试单击 'Insert Details Pane' 按钮,这将插入用户可以编辑的详细信息窗格(不使用本机 HTML <details/> 标记)。我希望详细信息显示在 'Summary' 框下方(在 y 轴上)和 'More text' 文本节点上方(在 z 轴上)。

但是,它不起作用。 'More text' 在窗格打开时向下移动。我希望使用 z-index 使详细信息窗格的详细信息框位于 'More text' 上方,从而使 'More text' 不动。没用。

看了很多类似的问题,发现

using 'top' and 'left'attributes can help ()

using relative positioning may also help (another question)

但是后来,我尝试了这两个,但都没有成功。

有人可以帮助我吗?提前致谢。

尽管 some websites claim 这...

z-index only works on positioned elements (position:absolute, position:relative, or position:fixed)

...唯一的 W3 代码示例使用 position:absolute。所以我们不能使用 position:relative 让元素相互堆叠。

参见 2015 年 10 月 CSS 3 WG 规范中的示例 16:https://drafts.csswg.org/css-position/#propdef-z-index

这里有一个 jsFiddle,说明了如何使用 position:absolute;

将浅灰色框放置在深灰色按钮上方