开发者

jQuery: shorten string length to fit a set width

I have a table, and in each cell I want to place strings, but they are much wider than the cell width. To prevent line break, I would like to shorten the strings to fit the cell, and append '...' at end to indicate that the string is much longer.

The table has about 40 rows and has to be done to each cell, so its import开发者_JAVA技巧ant that its a quick. Should I use JS/jQuery for this?

How would I do it?

Thank you for your time.

Kind regards,

Marius


You can use CSS -- text-overflow: ellipsis -- for this - with some caveats for certain browsers and workarounds listed here:

http://mattsnider.com/css/css-string-truncation-with-ellipsis/ (archived)


this should do the trick where 8 is is the the size of the text you want to keep

 $('td').each(function(){
    $(this).text($(this).text().substring(0,8)+"...");
 });

to answer you comment I think jquery width() should help get you going but I think your headed up a slippery slop you should consider something different like putting the text in a div or using flexigrid or jgrid


Use my jQuery plugin: jQuery-Shorten. It handles all the cases, makes use of text-overflow:ellipsis if available and it's very fast.

Download: github.com/MarcDiethelm/jQuery-Shorten

Demo & Doc: http://web5.me/jquery/plugins/shorten/shorten.doc.html

You can configure how the text ends (ellipsis). The default is a three-dot char ("…", …, Unicode: 2026) but you can use anything you want, including markup.

The text width of the 'selected' element (eg. span or div) is measured using Canvas or by placing it inside a temporary table cell and shortened (initially using an educated guess for efficiency) and measured again until it (and the appended ellipsis or text) fits inside the block. A tooltip on the 'selected' element displays the full original text.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜