简体   繁体   English

如何在不调整整体宽度的情况下隐藏表格行?

[英]How to hide table rows without resizing overall width?

Is there a way to hide table rows without affecting the overall table width?有没有办法在不影响整个表格宽度的情况下隐藏表格行? I've got some javascript that shows/hides some table rows, but when the rows are set to display: none;我有一些 javascript 可以显示/隐藏一些表格行,但是当这些行设置为display: none; , the table with shrinks to fit the contents of the visible rows. ,表格会缩小以适应可见行的内容。

If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set the width style property to this value:如果您希望保留表格的整体宽度,您可以在隐藏行之前检查它,并将宽度样式属性显式设置为此值:

table.style.width = table.clientWidth + "px";
table.rows[3].style.display = "none";

However, this may cause the individual columns to reflow when you hide the row.但是,当您隐藏行时,这可能会导致各个列重排。 A possible way to mitigate this is by adding a style to your table:缓解这种情况的一种可能方法是向您的表格添加样式:

 table {
  table-layout: fixed;
 }

CSS rule visibility: collapse was designed exactly for that. CSS 规则visibility: collapse正是为此而设计的。

tbody.collapsed > tr {
    visibility: collapse;
}

After adding this CSS you could trigger visibility from JS with:添加此 CSS 后,您可以通过以下方式触发 JS 的可见性:

tbody.classList.toggle('collapsed');

For reference, levik's solution works perfectly.作为参考,levik 的解决方案非常有效。 In my case, using jQuery, the solution looked something like this:就我而言,使用 jQuery,解决方案如下所示:

$('#tableId').width($('#tableId').width());

In CSS, table-layout: fixed;在 CSS 中, table-layout: fixed; on your table instructs the browser to honor the sizes you've specified for heights and widths.在您的桌子上指示浏览器遵循您为高度和宽度指定的尺寸。 This generally suppresses auto-resizing by the browser unless you haven't given any hints as to the preferred sizes of your rows and columns.这通常会禁止浏览器自动调整大小,除非您没有给出任何关于行和列的首选大小的提示。

You can do it using pure HTML您可以使用纯 HTML 来完成

 <table border="1"> <colgroup> <col width="150px" /> <col width="10px" /> <col width="220px" /> </colgroup> <tr> <td valign="top">1</td> <td> </td> <td>2</td> </tr> <tr> <td>3</td> <td> </td> <td>4</td> </tr> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM