好的,我找到了解决方案。 Fiddle here.
策略:
使用隐藏表格收集可见表格所需的单元格宽度。
战术:
除了用户应该看到的表格外,还必须在可见表格的正上方创建一个隐藏的“影子”表格,内容相同。
影子表必须允许内容包裹在单元格内(这是默认的table 行为)。
当页面加载完毕并且每次调整窗口大小时,show() 阴影表,测量顶行中每个td 的width,然后测量hide() 阴影表。然后将width 值复制到可见表中对应的td 元素中,该元素必须应用Chris Coyier's truncate。
适用于我测试过的所有浏览器,包括移动设备。
额外提示:
- 如有必要,使用
­ 换行长字,  停止换行。这只能在影子表中应用。
- 由于 Internet Explorer 中的错误,在影子表中使用
1px 更多单元格填充 - 否则,IE 的可见表有时会比影子表稍宽。
JavaScript(需要 jQuery):
<script type="text/javascript">
function loadEvents() {
initFluidTables();
}
// Resize fluid table(s)
function resizeFluidTables() {
// Show source cells
$( ".fluid-table-invisible-source" ).show(0);
var fluidTableCellWidth = [];
// Measure (normally invisible) source cells
$( ".fluid-table-invisible-source td" ).each(function( index, value ) {
fluidTableCellWidth[index] = $( this ).width();
});
// Resize (always visible) target cells. Adding 1 pixel due to apparent bug in Firefox.
$( ".fluid-table-visible-target td>i" ).each(function( index, value ) {
$( this ).css({'width': fluidTableCellWidth[index]+1 });
});
// Re-hide source cells
$( ".fluid-table-invisible-source" ).hide();
}
// Create table(s) to be fluid
function initFluidTables() {
// Create a container. Not really necessary, but keeps DOM tidier.
$(".fluid-table").wrap( "<div></div>" );
// This looks like a mess. What it does, is that .fluid-table duplicates itself, and each sibling gets a different class.
$(".fluid-table").each(function() {
$( this ).clone().appendTo( $( this ).addClass( "fluid-table-invisible-source" ).parent() ).addClass( "fluid-table-visible-target" );
});
// Add truncating element inside target cells
$(".fluid-table-visible-target td").wrapInner( "<i></i>");
// Truncate table contents at first drawing of the DOM and every time the window resizes
resizeFluidTables();
$( window ).resize(function() {
resizeFluidTables();
});
}
</script>
CSS:
.fluid-table td { padding-right: 5px; }
.fluid-table td:nth-child(odd) { color: #aaa; }
.fluid-table-visible-target td>i {
font-style: inherit;
white-space: nowrap;
display: block;
overflow: hidden;
text-overflow: ellipsis;
}
/* source slighly more padded than target due to IE bug */
.fluid-table-invisible-source td:nth-child(even) {
padding-right: 10px;
}
.fluid-table-visible-target td:nth-child(even) {
padding-right: 9px;
}
示例表:
注意使用&shy; 和&nbsp; 来指示您(不)希望在哪里截断文本。
<table class="fluid-table">
<tr>
<td>Avail­able <i>until</i>:</td><td>No expiry date</td><td>Avail­ability:</td><td>Worldwide</td><td></td>
</tr><tr>
<td>Year:</td><td>2016</td><td>Length:</td><td>29 minutes</td><td></td>
</tr><tr>
<td>First broad­cast:</td><td>Feb 2</td><td>Last broad­cast:</td><td>Feb 3</td><td></td>
</tr>
</table>