Dynamically shorten/hide/overlap tekst in table cells when too long

淺唱寂寞╮ 提交于 2019-12-25 04:29:46

问题


My table has static width values but sometimes table cells of a certain column can contain text which is too long and which messes up the table's width. I'm looking for a way to dynamically shorten text (kind of like a table grid functionality but then without grids) because it can be of a variable length, and when one hovers over the table cell the entire text is shown without stretching the table.

Currently, I have this hard coded in my script in the following way: string.substring(0, 65) + '...'; and passing the full text to the 'title' attribute of the table cell.

Note that I don't want to keep using the 'title' attribute. I tried surrounding the text with <span style='position: absolute; background: #EEE'></span> when triggered by the hovering event, but unfortunately that wasn't an appealing solution as the text moved a bit to the bottom while the padding nor the margin style were changed.

The solution can also be a jQuery plugin or JavaScript script.


回答1:


1. Shortening the original data

I suggest that you consider something more elegant than chopping the string at the 65th character. -- Instead, look for whitespace to break the string at. Only chop mid-word if no whitespace is found.

To save more room in the table cell, use the ellipses character… instead of three periods... Just copy/paste it from this answer. The ellipses character could also be styled with a different or smaller font.

2. Showing the original data on hover

I prefer YUI. Their tooltip widget works well for this. An example.




回答2:


You should try this CSS instruction:

td { break-word: word-wrap; }

that works in many browsers (yes, including IE 6, even IE 5.5 but not Fx 3.0. It's only recognized by Fx3.5+. Also good for Saf, Chr and Op but I don't know the exact version for these ones) and don't do any harm in the other ones.

If table's width is still messed up, there is also:

table { table-layout: fixed; }
th, td { width: some_value; }

that will force the browser to use the other table algorithm, the one where it doesn't try to adapt many situations including awkward ones but stick to what the stylesheet says.



来源:https://stackoverflow.com/questions/3249912/dynamically-shorten-hide-overlap-tekst-in-table-cells-when-too-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!