thead的宽度与tbody的td宽度不匹配

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

我想清空我的表td的内容,进行加载然后显示最新获取的数据,但问题是thead似乎有一些闪烁的问题,因为当tbody数据消失时thead的宽度会受到影响。

table {
  border-collapse: collapse;
}

table th,
table td {
  padding: 5px;
  border: 1px solid;
}

但是:ぁzxswい

javascript html css
3个回答
1
投票

这是正常的... https://jsfiddle.net/nLrpbz9r/1/元素不参与表宽度计算。您可以使用display: none代替:

visibility: collapse
$(function() {
  $('button').click(function() {

    const $tb = $("tbody");
    const new_visibility = $tb.css("visibility") === "visible" ? "collapse" : "visible";
    $("tbody").css({
      "visibility": new_visibility
    });

  });
});

不幸的是......当你在tbody中插入新数据时,宽度会根据内容而改变。除了使用固定布局表之外,没有好的解决方案。


0
投票

添加类似<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button>Toggle tbody</button> <table border="1"> <thead> <tr> <th>name</th> <th>age</th> </tr> </thead> <tbody> <tr> <td>john wesley</td> <td>18</td> </tr> </tbody> </table>的东西到你的CSS。

table th {min-width: 100px;}
$(function() {
  $('button').click(function() {
    const tb = $('tbody').clone()
    if ($(tb).length > 0) {
      $('tbody').hide()
    }
  })
})
table {
  border-collapse: collapse;
}

table th,
table td {
  padding: 5px;
  border: 1px solid;
}

table th {min-width: 100px;}

0
投票

我想我设置的这两个属性,我们将解决你的问题:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>name</th>
      <th>age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>john wesley</td>
      <td>18</td>
    </tr>
  </tbody>
</table>

<button>Hide tbody</button>

最后两行将每个td宽度的宽度固定为您想要的值(而不是200 px,最好将其设置为百分比值以支持责任),最后一行只是将文本放在中心位置。如果按下按钮,标题单元格将不会更改。

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