在Javascript/jQuery中的固定高度/宽度表格单元格中调整字体大小
我想制作一个具有固定高度/宽度单元格的可打印时间表. 单元格包含名称,但我不希望名称出现换行符.
I want to make a a printable schedule as table with fixed height/width cells. Cells contains names and I don't want that the names do line breaks.
有没有一种方法可以动态调整字体大小,从而不会出现换行符或隐藏文本?
Is there a way to dynamically adjust the font-size so that there will be no linebreaks or hiding text?
也许有人知道该问题的好插件或摘要?
Maybe someone knows a good plugin or snippet for that issue?
尝试用white-space: nowrap
和overflow: hidden
将每个单元格的内容包装到另一个元素(表单元格不支持overflow :hidden
),并减小font-size
,直到其内容适合其中为止.
Try wrapping the contents of each cell with another element (table cells don't support overflow :hidden
) with white-space: nowrap
and overflow: hidden
and reducing the font-size
of that element until it's contents fit into it.
示例代码:
HTML:
<table>
<tbody>
<tr>
<td><span>cell</span></td>
<td><span>another cell</span></td>
<td><span>yet another cell</span></td>
</tr>
</tbody>
</table>
CSS:
td span {
display: block;
white-space: nowrap;
width: 100px;
overflow: hidden;
font-size: 100%;
}
JS:
$(function() {
$('td span').each(function() {
var fontSize = 100;
while (this.scrollWidth > $(this).width() && fontSize > 0) {
// adjust the font-size 5% at a time
fontSize -= 5;
$(this).css('font-size', fontSize + '%');
}
});
});