html元素的最大字符串长度

时间:2013-05-30 08:32:17

标签: javascript jquery html string-length

我有一些推文在我的网站上被提取,每个推文长度不同,但我想确保它们一直显示在一行上。

这是它们应该出现的方式:

twitter string length

然而,如果推特长度超过这么多单词,它就会落到下一行,并与设计混淆。

我的问题是给这个字符串或div? (请原谅我的理解不够)最长?然后可能如果我们达到最大字符串长度以在字符串的末尾添加省略号(...)。

我头脑中的想法就像#div> 120然后将字符串缩短为120并添加(...)。有人可以帮助我实现这一目标吗?不确定javascript / jQuery是否可以去这里?谢谢!

3 个答案:

答案 0 :(得分:3)

你可以简单地使用CSS来做到这一点,而无需在JS或jQuery中进行任何计算。

为要显示推文的div元素定义固定宽度,并将css类省略号应用于该元素:

.Ellipsis
{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

希望有所帮助

答案 1 :(得分:0)

在Javascript中,您可以使用substring方法。

var value = "This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.";

function truncate(value, length){
   return value.substring(0,300);
}

alert(truncate(value,3000));

<强> Working Example

答案 2 :(得分:0)

我会使用slice()方法:

var formatted_tweet = long_tweet.slice(0, 120) + "...";

或以function形式:

function trim(str, len) {
    return(str.slice(0, len) + "...");
}

var formatted_tweet = trim(long_tweet, 120);