new*_*967 5 javascript html-table width
我是网络编程的新手,所以我可能在这里犯了一些明显的错误.
当我试图在诸如rows [i] .style.display ='none'之类的javascript中隐藏表中的行时,表格布局会完全破坏.最初,细胞内容被包裹起来,桌子的宽度也在缩小.然后我在table标签中添加了style ="table-layout:fixed",并在每个td中添加了style ="white-space:nowrap".这会阻止换行,但内容仍然没有在一行上对齐.如果空间和列宽从一行到另一行变化,则单元格开始向左移动.然后,我为每个th和td元素以及包含该表的div添加了固定宽度.问题仍然存在.
我目前的HTML类似于以下内容.
<div style="width: 300px">
<table id="errorTable" width="100%" cellpadding="5" cellspacing="2" style="table-layout: fixed">
<tr id="HeaderRow">
<th style="width: 100px;">Header 1</th>
<th style="width: 50px;">Header 2</th>
<th style="width: 150px;">Header 3</th>
</tr>
<tr id="DetailRow1">
<td style="white-space:nowrap; width: 100px;">Data 1_1 in Row 1</td>
<td style="white-space:nowrap; width: 50px;">Data 1_2 in Row 1</td>
<td style="white-space:nowrap; width: 150px;">Data 1_3 in Row 1</td>
</tr>
<tr id="DetailRow2">
<td style="white-space:nowrap; width: 100px;">Data 2</td>
<td style="white-space:nowrap; width: 50px;">Data 2</td>
<td style="white-space:nowrap; width: 150px;">Data 2</td>
</tr>
<tr id="DetailRow3">
<td style="white-space:nowrap; width: 100px;">Data 3_1</td>
<td style="white-space:nowrap; width: 50px;">Data 3_2</td>
<td style="white-space:nowrap; width: 150px;">Data 3_3</td>
</tr>
</table>
</div>
Run Code Online (Sandbox Code Playgroud)
当第一次显示表格时,列正确对齐,宽度分别为100,50和150像素.但是如果有一行,比如第二个被隐藏,则剩下的两个显示行的单元格宽度不再固定为100,50和150,并且数据不再垂直对齐.请注意,整个桌子宽度仍然是300像素.如果有可用空间,则每个单元格中的数据向左移动,并且最后一个使用额外空间,在本例中为第三列.
正如您所看到的,以下帖子很有帮助,但没有完全解决我的问题. 隐藏表行而不调整整体宽度
我们非常欢迎任何帮助.
小智 5
问题在于您用来使表行可见的显示类型。
要隐藏表行,请使用display="none"
要显示表行,请使用display="table-row"
我做了一个示例,以便您可以看到它们的实际效果。
function show(){
document.getElementById('trB').style.display='table-row';
}
function hide(){
document.getElementById('trB').style.display='none';
}Run Code Online (Sandbox Code Playgroud)
@import url("https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css");
table{
border: 1px solid #ccc;
}Run Code Online (Sandbox Code Playgroud)
<table id="myTable" class="table table-striped table-hover">
<thead>
<tr>
<td>#</td>
<td>Letter</td>
</tr>
</thead>
<tbody>
<tr id="trA">
<td>1</td>
<td>A</td>
</tr>
<tr id="trB">
<td>2</td>
<td>B</td>
</tr>
<tr id="trC">
<td>3</td>
<td>C</td>
</tr>
</tbody>
</table>
<button id="showB" onclick="show()">show B</button>
<button id="hideB" onclick="hide()">hide B</button>Run Code Online (Sandbox Code Playgroud)
始终固定列的宽度。这会解决你的问题吗?
.myTable td{ width:33% !important; }
Run Code Online (Sandbox Code Playgroud)
thead理想情况下,您还应该使用和括起标题和正文部分tbody
<table>
<thead>
<tr> ... </tr>
</thead>
<tbody>
.
.
.
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)