我有一个包含多个单元格的100%宽度表。我希望其中一个单元格始终在一行white-space: nowrap
中显示其内容,如果内容超过表单元格text-overflow: ellipsis
,则在该行末尾显示省略号。
我遇到的问题是,当达到单元格内容时,表将停止收缩。因此,单元格的最小宽度始终是其内容的宽度,而表将作为一个整体推出。
我只是不知道如何解决这个问题:
我的HTML:
<div class="otrCompactView">
<div class="otrLastEditTable">
<div class="otrLastEditRow">
<div class="otrLastEditor">LastEditor</div>
<div class="otrLastEdited">LastModified</div>
</div>
</div>
<div class="otrTitleRow otrRow">
<div class="otrTitle">Title asdasdasdas asd asd asd asdas as asd </div>
</div>
<div vlass="otrTaskRow otrRow">
</div>
<div class="otrColumnsRow otrRow">
<div class="otrColumns"></div>
</div>
</div>
我的CSS:
.otrCompactView {
display: table;
background: yellow;
width: 100%;
height: 100%;
}
.otrRow {
display: table-row;
}
.otrLastEditTable {
display: table;
width: 100%;
}
.otrLastEditRow {
display: table-row;
}
.otrLastEditor {
display: table-cell;
}
.otrLastEdited {
display: table-cell;
text-align: right;
}
.otrTitle {
border: 1px dotted red;
min-width: 50px;
white-space: nowrap;
}
直接测试的小提琴:
http://jsfiddle.net/67B6G/
这看起来像你想要的吗?
更新
HTML
<div class='table'>
<div class='row'>
<div class='cell'>Something quite long</div>
</div>
<div class='row'>
<div class='cell'>
here is some moreSomething quite long that should exceed the table cell.Something quite long that should exceed the table cell.
</div>
</div>
</div>
CSS
.table{
margin:0;
padding:0;
display:table;
table-layout: fixed;
width:100%;
max-width:100%;
}
.row{
display:table-row;
}
.cell{
display:table-cell;
border:1px solid grey;
}
.cell:last-child{
white-space: nowrap;
overflow:hidden;
text-overflow: ellipsis;
}
这里有一种不使用table-layout: fixed
的方法,它允许您使用jQuery保持动态宽度。
HTML:
<div class="table">
<div class="left">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
<div class="right">Lorem Ipsum</div>
</div>
在CSS中,您使用标准省略号代码,但添加了max-width: 0
(如这里针对实际table
元素所解释的):
.table {
display: table;
width: 100%;
}
.left, .right {
display: table-cell;
padding: 0 5px 0 5px;
max-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
如果就此打住,那么每个子div
将占父div
总宽度的50%,因此您仍然无法适应内容动态宽度。为了解决这个问题,我修改了这段代码,它计算元素中文本的宽度,以计算宽度,然后使用它来动态设置右列的宽度。然后,左列将具有省略号。
// Calculate width of text from DOM element or string. By Phil Freo <http://philfreo.com>
$.fn.textWidth = function(text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};
$('.right').on('input', function() {
var $width = $(this).textWidth(); // Get width of text
$width += 10; // Add left and right padding
$(this).width($width); // Set width
}).trigger('input');
请注意,上面的代码要求您考虑padding
;否则,右列也将有省略号。这是一把小提琴。
要在具有多行的表中使用此功能,可以修改jQuery对列中的单元格进行迭代,并将列的宽度设置为列中最宽单元格的必要宽度。或者,如果您知道哪一个是最宽的,您可以直接使用jQuery来获得它的宽度。