检测表格中溢出的行

3
我有一个任意高度的表格。行是通过JavaScript动态填充的。当添加新行时,我不希望表格超过其高度。新行添加到表格顶部,旧行应从表格底部删除。是否有一种方法可以检测行是否溢出?如图所示,行f、g、h、i应被删除。

enter image description here

.cnt {
    width: 100vw;
    height: 50vh;
    max-width: 100vw;
    max-height: 50vh;
    text-align: center;
    border: 1px solid black;
}
section {
  height: 100%
}
table {
  display: block;
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;  
  overflow: hidden;
}
table tbody tr td{
  margin: 0;
  padding: 0; 
}
<html>
  <body>
    <div class="cnt">
      <section>
        <table>
          <tbody>
            <tr><td>a</td></tr>
            <tr><td>b</td></tr>
            <tr><td>c</td></tr>
            <tr><td>d</td></tr>
            <tr><td>e</td></tr>
            <tr><td>f</td></tr>
            <tr><td>g</td></tr>
            <tr><td>i</td></tr>
          </tbody>
        </table>
      </section>
    </div>
  </body>
</html>


你可以尝试这个代码- .table ,.table tbody>tr>td{ table-layout:fixed;
white-space: nowrap; overflow: hidden;
}
- piedpiper
1个回答

1
当您添加一行时,请计算所有行的汇总高度,并删除冗余行。

clear();

function clear() {
  const table = document.querySelector('table');
  let sum = 0;
  let i = 0;
  while (i < table.rows.length) {
    let h = table.rows[i].clientHeight;
    if (sum + h > table.clientHeight) {
      table.deleteRow(i);
    } else {
      sum += h;
      i++;
    } 
  }
}
.cnt {
  height: 50vh;
  border: 1px solid black;
}

section {
  height: 100%;
}

table {
  display: block;
  height: 100%;
}
<html>
  <body>
    <div class="cnt">
      <section>
        <table>
          <tbody>
            <tr><td>a</td></tr>
            <tr><td>b</td></tr>
            <tr><td>c</td></tr>
            <tr><td>d</td></tr>
            <tr><td>e</td></tr>
            <tr><td>f</td></tr>
            <tr><td>g</td></tr>
            <tr><td>i</td></tr>
          </tbody>
        </table>
      </section>
    </div>
  </body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接