假设我有一个如下表:
|<-- Fixed width ->|
|<- group width ->|<- group width ->|
--------------------------------------------------------------------
| Label 1 | Input 1 | Label 2 | Input 2 | Filler (auto-expand) |
| Label 3 | Input 3 | Label 4 | Input 4 | |
| Section header (colspan=5) |
--------------------------------------------------------------------
| Label 5 | Input 5 | Label 6 | Input 6 | |
| Label 7 | Input 7 | Label 8 | Input 8 | |
--------------------------------------------------------------------
我将如何设置样式,以使每个列组具有固定的宽度,但每个组下的各个列会自动调整,如下所示:
标签列调整为显示该列文本而无需换行所需的最小宽度
输入列将展开以填充组宽度减去标签列宽度后剩下的空间。
例:
|<-- Fixed width ->|
|<- group width ->|<- group width ->|
--------------------------------------------------------------------
| Label 1 | Input 1 | Label 2 | Input 2 | Filler (auto-expand) |
| Label 3.. | Input 3 | Label 4 | Input 4 | |
| Section header (colspan=5) |
--------------------------------------------------------------------
| Label 5 | Input 5 | Label 6 | Input 6 | |
在上面,包含标签1、3和5的标签列已调整为所有要显示的文本不被截断所需的最小宽度(标签3的宽度)。同时,对相应的输入列进行了调整,以使组宽度保持不变。
我有一个jsfiddle的结构和初始CSS here。
如果需要,可以随意调整结构,尽管我希望对其进行最小的更改。我希望仅通过html结构更改和CSS就能实现。
我也欢迎jquery解决方案。尽管我还应该提到标签/输入行可以动态添加,并且列需要适当调整(所以我不能只在初始文档加载时设置固定宽度)。
如果还可以更改它,以便不再需要表,那更好。
最佳答案
您要的是this吗?如果是,请查看以下代码
// Assume you want widths 60, 90, 120 widths to each header
var widths = [60, 90, 120];
$('table td[colspan]').each(function (i, v) {
var th = $(this),
width = Math.floor(widths[i] / th.attr('colspan') * 1),
indStrt = 0;
th.width(widths[i]);
th.prevAll().each(function () {
var ind = $(this).attr('colspan');
indStrt += ind ? ind * 1 : 1;
});
var nextTr = th.closest('tr').next(),
tds = nextTr.find('td');
var $siblings = tds.eq(indStrt).nextUntil(tds.eq(indStrt + th.attr('colspan') * 1)).andSelf();
$siblings.each(function () {
$(this).width(width);
});
});
根据评论代码是
var COLUMN_GROUP_WIDTH=100;
var TABLE_WIDTH=$("#thetable").width();
// reset width so we can get proper column widths
$("#thetable").width("auto");
$('td.label').each(function (e, v) {
var labelWidth = $(v).width();
$(v).width(labelWidth);
console.log(labelWidth);
$(v).next().width(COLUMN_GROUP_WIDTH-labelWidth);
});
// so we can check total widths
//$(".header").css("display", "table-row");
$("#thetable").width(TABLE_WIDTH);