如何使添加到表中的新行位于具有 z-index 的其他元素之上

问题描述 投票:0回答:1

我有一个表格,每次按“提交”按钮时都会向其中添加行。

我的目标:我希望添加到表格中的行位于表单元素的顶部并覆盖它。

问题:现在发生的情况是,添加的新行只是下推表单和 btn。 z-index 不会生效。

注意代码有:

  1. '位置:相对'

  2. z-index 设置正确

3.stack 上下文似乎也正确

如何在不使用“位置:绝对”的情况下做到这一点?

我知道绝对位置将其从流程中取出,但它改变了布局,所以我不想这样做。

尽管我研究过并观看了教程,但在任何地方都找不到解决方案。

这是我得到的:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
   
    <table id="myTable">
      <thead>
       <tr>
        <th>Name</th>
        <th>Number</th>
       </tr>
    </thead>
    <tbody>

    </tbody>
    </table>

    <form>
      <label for="fName">Name</label><br />
      <input type="text" id="fName" name="fName" /><br />
      <input type="submit" id="submitBtn" />
    </form>
 
    <script src="index.js" charset="utf-8"></script>
  </body>
</html>

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  }
  

table {
  color: red;
  width: 200px;
  padding: 15px;
  margin: 15px;
  border-collapse: collapse; 
  position: relative;
  z-index: 1;

}

thead{
  border: solid 3px blue;
}


.tr{
border-bottom: solid 1px black;
color: green;

}


form{
  position: relative;
  z-index: 0;
}
"use strict";

let inputBox = document.querySelector("#fName");
let tBody = document.querySelector("tbody");


function addRow() {
  let row = tBody.insertRow(0);
  let cell1 = row.insertCell(0);
  let cell2 = row.insertCell(1);
  cell1.innerHTML = inputBox.value;
  cell2.innerHTML = "text2";
  inputBox.value = " ";
  row.classList.add('tr');
  
}

document.querySelector("#submitBtn").addEventListener("click", function (event) {
    event.preventDefault();
    addRow();
  });

  

非常感谢

css html-table z-index
1个回答
0
投票

我认为您还不明白改变

z-index
到底是做什么的。更改 z 索引与元素的实际流无关——无论元素是否具有相同的 z 索引值,它改变的只是堆叠顺序(即它们如何重叠)。添加这些新行将扩展表格的高度,自然地将表格推向页面下方,无论 z 索引值如何。这并不是说提供表格
z-index: 0
实际上会将其放入屏幕更深的位置并防止桌子将其向下推。

如果您希望表格与表单重叠,您需要使用绝对定位。您可以尝试将表格和表单包装在

<div>
中,并在表单上使用绝对定位,使其与 div 顶部保持一定的距离。这会将其固定到位并允许桌子与其重叠。像这样(为简洁起见缩短):

HTML

<body>
  <div class="container">
    <table id="myTable">
      <!-- ... -->
    </table>

    <form>
      <!-- ... -->
    </form>

    <script src="index.js" charset="utf-8"></script>

  </div>
</body>

CSS

.container {
  position: relative;
}

form{
  position: absolute;
  z-index: 0;
  top: 50px;
}

虽然我想知道为什么你会希望新的表格行覆盖表单元素。

© www.soinside.com 2019 - 2024. All rights reserved.