0

我有一个显示一堆文本的 div,但我只想显示 75 个字符,其余文本被替换为 ...

<div class="text-info">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation</div>

$('text-info').replaceWith(this).length(75 + "...");
4

4 回答 4

6
var text = $(".text-info").text();
var len = text.length;

if(len > 75){
  $(".text-info").text($(".text-info").text().substr(0,74)+'...  ');
}
于 2013-04-24T19:26:28.030 回答
1

从字面上理解您的问题,如果您只想显示 75 个字符,那么您可以简单地按照@MohammadAdil 的建议进行操作。但是,您最终会得到 79 个字符(74 + 3 (...) + 两个空格。只需通过拉出 72 个字符并附加"...". 来限制它。当然,如果您实际上需要限制为 75 个可见字符,或者如果您只是指帖子的 75 个字符,然后添加省略号。

我个人的建议是把它留给一个可以为你做的图书馆(或者如果可以的话,使用一个)。Underscore是一个相当小的库,其中包含大量方便的实用程序,它可以确定您是否可以内置与它们的实现(例如_.each使用Array#forEach是否已定义)。话虽这么说,underscore.string是下划线的一个插件,它包含许多有用的字符串操作函数,比如_.toSentence它会接受和数组一样["one", "two", "three"]并返回"one, two and three",但更重要的是你得到truncateand prune

truncate并且prune仅在字符串处于其限制时才执行截断,例如,根据他们的示例:

// Assume the underscore.string functions have bene mixed into _
_.truncate("Hello, World", 5) // "Hello..."
_.truncate("Hello", 10) // "Hello"

truncate函数将剪切文本中间句子,这prune是一个更干净的替代方案,因为它在最接近指定长度的分词处剪切文本。根据他们的例子:

_.prune("Hello, cruel world", 15) // "Hello, cruel..."
// for comparison
_.truncate("Hello, cruel world", 15) // "Hello, cruel wo..."
于 2013-04-24T19:39:58.280 回答
0

你可以试试这个

$(".text-info").text(function(){
    return $(this).text().length > 75 ? $(this).text().substr(0, 75)+'...' : $(this).text();
});

演示。

于 2013-04-24T19:31:12.477 回答
0

像这样的东西会起作用:

(".text-info").text($(this).text().substr(0, 75)+'...');

另外,不要忘记选择器中的类标识符。.

于 2013-04-24T19:22:20.437 回答