使用基于像素宽度的jQuery截断文本

我正在尝试使用jquery编写一个快速函数来计算html页面上字符串的像素宽度,然后截断字符串直到达到理想的像素宽度…

但是它不起作用(文本没有截断)……

这是我的代码:

function constrain(text, original, ideal_width){ var temp_item = (''+ text +''); $(temp_item).appendTo('body'); var item_width = $('span.temp_item').width(); var ideal = parseInt(ideal_width); var smaller_text = text; while (item_width > ideal) { smaller_text = smaller_text.substr(0, (smaller_text-1)); $('.temp_item').html(text); item_width = $('span.temp_item').width(); } var final_length = smaller_text.length; if (final_length != original) { return (smaller_text + '…'); } else { return text; } } 

这是我从页面调用它的方式:

  $('.service_link span:odd').each(function(){ var item_text = $(this).text(); var original_length = item_text.length; var constrained = constrain(item_text, original_length,175); $(this).html(constrained); }); 

关于我做错的任何想法? 如果有办法更快地完成它(即冒泡排序),那也会很棒。

谢谢!

为什么不使用CSS来指定要将此字符串放入的元素的宽度,而不是将其与脚本一起攻击? 您可以使用text-overflow来告诉浏览器它应该用省略号截断。

 .truncated { display:inline-block; max-width:100px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } 

text-overflow是CSS3声明,但在IE 6 +,WebKit 312.3+(Safari 1.3 + / Chrome)和Opera 9+(版本<10.7需要-o-text-overflow声明)中受支持。

请注意,这在Firefox中未实现,直到7.0,并且不到4%的Firefox用户仍在使用旧版本(大多数是3.6)。 在旧版本中,您的文本仍将被截断,不会呈现省略号。 如果您担心这一小组用户,可以使用这个jQuery插件 ,它在IE / WebKit / Opera /Firefox≥7中什么都不做,但会在Firefox≤6中模拟text-overflow

在这一行:

smaller_text = smaller_text.substr(0, (smaller_text-1));

你可能有意

smaller_text = smaller_text.substr(0, (smaller_text.length-1));

这会解决问题吗?

谢谢,我让它工作 – 但它只适用于第一项并停止,这是否与我声明变量的方式有关?

这是当前的代码:

  function constrain(text, original, ideal_width){ var temp_item = (''); $(temp_item).appendTo('body'); var item_width = $('span.temp_item').width(); var ideal = parseInt(ideal_width); var smaller_text = text; while (item_width > ideal) { smaller_text = smaller_text.substr(0, (smaller_text.length-1)); $('.temp_item').html(smaller_text); item_width = $('span.temp_item').width(); } var final_length = smaller_text.length; if (final_length != original) { return (smaller_text + '…'); } else { return text; } } 

该函数需要检查文本,像素中的ideal_width和css的类名。 如果ideal_width小于文本宽度,则截断并添加hellip,否则返回未修改的文本。 简单而有效! 🙂

 function constrain(text, ideal_width, className){ var temp_item = (''); $(temp_item).appendTo('body'); var item_width = $('span.'+className+'_hide').width(); var ideal = parseInt(ideal_width); var smaller_text = text; if (item_width>ideal_width){ while (item_width > ideal) { smaller_text = smaller_text.substr(0, (smaller_text.length-1)); $('.'+className+'_hide').html(smaller_text); item_width = $('span.'+className+'_hide').width(); } smaller_text = smaller_text + '…' } $('span.'+className+'_hide').remove(); return smaller_text; } 

如果你有文字,并知道你想要的大小,为什么不只是使用substr?

我做了类似的事情

 $('#history-1').text( $('#history-1').text().trim().substr(0,32) + "..." )