jQuery 文本截断(阅读更多样式)

标签 jquery text trim

我的问题与“Trim text to 340 chars”非常相似,但是是在jQuery中。这听起来很简单,但当我四处搜索时,我找不到任何引用资料。

好的,我有一个 div $('#content') 我想将文本修剪为 'x' 个字符,可以说 '600' BUT 我不想让它自己破坏这个词!就像不是“问题...”而是“问题...”。

文本的其余部分会发生什么?好吧,我将其隐藏并根据要求显示它!但是等等,它应该首先删除“...”并在其隐藏位置之后显示文本。

这是 $('#content') 的示例结构:

<div id="content">
    <p>Once upon a midnight dreary, while I pondered weak and weary,Over many a quaint and curious volume of forgotten lore.</p>
    <p>Writing example text is very boring.</p>
    <p>Specially when you are dumb enough not to copy and paste. Oh!</p>
    <p>Once it sheltered the rogues and rapscallions of the British Empire; now Kangaroo Island is ready and waiting for some derring-do of your own. Venture into the rugged wilds of the island, traversing untamed bushland and pristine beaches seeking out seal, penguin and sea lion colonies. Meet the land loving locals - koalas, goannas, echidnas and the island's own species of kangaroo. </p>
</div>

如何加载:

Once upon a midnight dreary, while I pondered weak and weary,Over many a quaint and curious volume of forgotten lore.

Writing example text is... [Read More]

点击“阅读更多”后:

Once upon a midnight dreary, while I pondered weak and weary,Over many a quaint and curious volume of forgotten lore.

Writing example text is very boring.

Specially when you are dumb enough not to copy and paste. Oh!

Once it sheltered the rogues and rapscallions of the British Empire; now Kangaroo Island is ready and waiting for some derring-do of your own. Venture into the rugged wilds of the island, traversing untamed bushland and pristine beaches seeking out seal, penguin and sea lion colonies. Meet the land loving locals - koalas, goannas, echidnas and the island's own species of kangaroo.

<小时/>

更新: 我发现这两个插件的工作与这个最佳答案基本相同。然而,最好的答案有一些这些插件没有的功能,反之亦然!

最佳答案

如果您不介意丢失段落标签,以下内容可用于限制文本量。

<script type="text/javascript">
var shortText = $("#content").text()    // get the text within the div
    .trim()    // remove leading and trailing spaces
    .substring(0, 600)    // get first 600 characters
    .split(" ") // separate characters into an array of words
    .slice(0, -1)    // remove the last full or partial word
    .join(" ") + "..."; // combine into a single string and append "..."
</script>

关于jQuery 文本截断(阅读更多样式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2248742/

相关文章:

jquery - 仅当父 div 在 View 中时显示固定按钮

javascript - 无需点击即可淡出

javascript - 在选择框 jquery 中选择选项和过滤值

javascript - 即使正确导入,jqGrid 也不可用

java - 如何在JPanel中添加一个可编辑的文本框

jquery - 使用文本淡入播放声音

php - 使用未定义的常量 STDIN - 在第 5 行的 C :\wamp\www\study\sayHello. php 中假定为 'STDIN'

javascript - 删除值提示中字符串之间的空格

java - 如何让SmartGWT标签的内容不删减空格?

react-native - 文本和 TouchableOpacity 文本未出现在直线中