jQuery 如何将 div 的内部文本限制为 175 个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6983912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:39:13  来源:igfitidea点击:

How to limit inner text of div to 175 characters?

jquery

提问by TruMan1

I have a div area that has an arbitrary number of characters. I want to limit the amount of characters that show up in there to 175 characters. I mostly found exaple on how to do this for a input text box or text area, but not a div. Can anyone help with this?

我有一个具有任意数量字符的 div 区域。我想将其中显示的字符数限制为 175 个字符。我主要找到了关于如何为输入文本框或文本区域执行此操作的示例,而不是 div。有人能帮忙吗?

This is my code I am trying to limit to 175 characters:

这是我试图限制为 175 个字符的代码:

<div class="some-area">
Blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
</div>

回答by Frédéric Hamidi

You can use the the form of text() that takes a functionand write something like:

您可以使用带有函数的 text() 形式并编写如下内容:

$("div.some-area").text(function(index, currentText) {
    return currentText.substr(0, 175);
});

回答by RobB

Replace div with the correct identifier for your content:

将 div 替换为您的内容的正确标识符:

$("div").text($(this).text().substr(0, 175)+'...');

Remove the ellipses from the end if desired. I would recommend leaving them to let your users know that the text was shortened. If you are just trying to limit the text to 175 without any notice, then you may choose to remove them in that case as well.

如果需要,从末尾删除椭圆。我建议让他们让你的用户知道文本被缩短了。如果您只是想在没有任何通知的情况下将文本限制为 175,那么您也可以在这种情况下选择删除它们。

回答by Phil

I just did this for one of my projects. I found thisgreat plugin.

我只是为我的一个项目做了这个。我发现了这个很棒的插件。

$('some-area').expander({
    slicePoint:175
});

回答by Nouman Saleem

var textis="";textis=$(".some-area").html().substring(0, 175);$(".some-area").html(textis);

回答by Chris Laplante

Instead of just cutting it off at 175 characters, add an ellipsis to the div if the text runs over the maximum width: https://web.archive.org/web/20110828173959/http://plugins.jquery.com/plugin-tags/ellipsis

如果文本超过最大宽度,不要在 175 个字符处将其截断,而是向 div 添加省略号:https: //web.archive.org/web/20110828173959/http: //plugins.jquery.com/plugin -标签/省略号