
本文旨在解决表格中某一列如何根据可用空间自动调整宽度,并在新增列时能够收缩自身宽度以适应布局的需求。通过 CSS 的 max-width 属性和 text-overflow: ellipsis 属性,以及 JavaScript 事件监听器的使用,实现表格列的自适应宽度和收缩,避免表格超出容器范围,并提供友好的文本溢出显示。
在构建动态表格时,经常会遇到需要某一列自动填充剩余空间,并且在新增列时能够自动收缩自身宽度的情况。以下提供一种使用 CSS 和 JavaScript 实现此功能的方案。
首先,定义 HTML 结构,包含一个表格容器 tableContainer,一个表格 table,表头 thead 和表体 tbody。其中,需要自适应宽度的列具有 variCol 类,固定宽度的列具有 fixedCol 类。
<div id="tableContainer">
<table id="table">
<thead>
<tr id="headRow">
<td class="fixedCol">Column 1</td>
<td class="variCol">Variable Width Column: Use available</td>
</tr>
</thead>
<tbody id="body">
<tr id="row1">
<td class="fixedCol">Current Behavior</td>
<td class="variCol">table width expands beyond container </td>
</tr>
<tr id="row1">
<td class="fixedCol">Desired Behavior</td>
<td class="variCol">Width of this column to shrink to make room for new columns </td>
</tr>
</tbody>
</table>
</div>
<span id="myButton">Add Column</span>关键的 CSS 样式如下:
立即学习“前端免费学习笔记(深入)”;
.variCol {
position: relative;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 150px; /* 设置最大宽度 */
vertical-align: top;
background-color: yellow;
}
.fixedCol {
position: relative;
width: 150px;
}
table {
position: relative;
width: 700px;
max-width: 100%;
height: 200px;
border: 1px solid black;
}
#myButton {
background-color: lightgray;
cursor: pointer;
}
#tableContainer {
position: relative;
width: 700px;
height: 300px;
border: 1px solid black;
}使用 JavaScript 动态添加列,并使用事件监听器替代内联事件处理。
function AddColumn() {
const body = document.getElementById("body");
const head = document.getElementById("headRow")
const row1 = document.getElementById("row1");
let el = document.createElement("td");
const cols = head.childElementCount + 1;
el.className = "fixedCol";
head.append(el);
el.textContent = "Column " + cols;
el = document.createElement("td");
el.className = "fixedCol";
row1.append(el);
}
document.getElementById("myButton").addEventListener('click', AddColumn)通过结合 CSS 的 max-width 和 text-overflow: ellipsis 属性,以及 JavaScript 的动态添加列功能,可以实现表格列的自适应宽度和收缩,从而更好地适应不同的布局需求,并提供良好的用户体验。
以上就是使用 CSS 实现表格列的自适应宽度与收缩的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号