2011-08-25 74 views
11

假设我们有一个<div style="width:100px;">This text is too long to fit</div>用“...”代替太长的字符串

div中的文本是动态的。我想强制文本宽度适合,而不是打破。 所以我需要某种功能来测试文本是否适合,如果不适合,那么我想显示实际适合的文本部分。最后追加...

结果了太长时间的文字应该是这样的:"This text is..."

是否有这样做我想要的一些标准的方式吗?通过javascript,jquery,jsp或java?

谢谢!

编辑: 感谢您的快速和许多答案!我通过猜测有多少个字符适合用java来做这件事。这似乎不是一个最佳的解决方案,所以我才来到这里。

css解决方案对我来说非常完美。它没有那么大的一个交易,它不适用于Firefox,因为我的客户都使用即无论如何。 :)

+1

你甚至可以使用CSS http://stackoverflow.com/questions/802175/truncating-long-strings-with-css-feasible-yet – sod

回答

24

,你可以用text-overflow:ellipsishttp://www.css3.com/css-text-overflow/

,或者如果你坚持使用JS的方式,你可以用你的DIV中的文本节点,然后用与比较包裹的宽度CSS3做的父母。

+1

+1!整洁的解决方案 – GETah

5
if(text.length > number_of_characters) { 
    text = text.substring(from, to); 
} 
+0

JavaScript字符串没有长度方法,但是有一个属性。即代码需要'if(text.length> number_o ...' – Pylinux

+0

@Pylinux感谢通知,修正了问题:) – evilone

0

如果添加id标签到div支持,你可以用document.getElementById("divid").innerHTML得到div的内容。从那里,你可以使用.length来获得字符串的长度。如果字符串的长度超过了某个阈值,只需要一个子字符串并附加一个“...”。

但是,如果可以的话,你应该尝试做这个服务器端。依靠Javascript/CSS为用户正确格式化是一个不太理想的解决方案。

7

,如果你要处理的数据,你可以使用一个函数:

function TextAbstract(text, length) { 
    if (text == null) { 
     return ""; 
    } 
    if (text.length <= length) { 
     return text; 
    } 
    text = text.substring(0, length); 
    last = text.lastIndexOf(" "); 
    text = text.substring(0, last); 
    return text + "..."; 
} 

text = "I am not the shortest string of a short lenth with all these cows in here cows cows cows cows"; 

alert(TextAbstract(text,20)); 

编辑:过程中的所有分度,多余长度的文本:

var maxlengthwanted=20; 

    $('div').each(function(){ 
     if ($('div').text().length > maxlengthwanted) 
      $(this).text(TextAbstract($(this).text())); 
    }); 
0

更可能的情况是,你因为它有自己的字体等等,所以不可能知道将有多少个字符适合dom元素。 CSS3目前不是一个选项(无论如何)。所以,我创建了一个小格屏幕外,并保持干扰测试串入,直到宽度是正确的:

var text = 'Try to fit this text into 100 pixels!'; 
var max_width = 100; 

var test = document.createElement('div'); 
test.className = 'Same Class as your real element'; // give it the same font, etc as a normal button 
test.style.width = 'auto'; 
test.style.position = 'absolute'; 
test.style.left = '-2000px'; 
document.body.appendChild(test);    
test.innerHTML = text; 

if ($(test).width() > max_width) { 

    for (var i=text.length; i >= 0; i--) { 
     test.innerHTML = text.substring(0, i) + '...'; 
     if ($(test).width() <= max_width) { 
      text = text.substring(0, i) + '...'; 
      break; 
     } 
    } 
} 

document.body.removeChild(test);