javascript jQuery 插件“readmore”,修剪文本而不切割单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5838591/
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
jQuery Plugin "readmore", trim text without cutting words
提问by Santiago
I'm using http://rockycode.com/blog/jquery-plugin-readmore/for trim long text and add a "See more" link to reveal all the text.
我正在使用http://rockycode.com/blog/jquery-plugin-readmore/修剪长文本并添加“查看更多”链接以显示所有文本。
I would love to avoid cutting words, how could I do that?
我很想避免切词,我该怎么做?
If the limit is 35, don't cut the w...
如果限制为 35,请不要削减 w...
but
但
If the limit is 35, don't cut the word... (and in this case, trim it at 38 and then show the hidden text from 39th chtill the end.
如果限制是 35,不要剪掉这个词......(在这种情况下,在 38 处修剪它,然后从 39 到最后显示隐藏的文本。
采纳答案by mVChr
You can change the abridge
function within that plugin as follows:
您可以abridge
按如下方式更改该插件中的功能:
function abridge(elem) {
var opts = elem.data("opts");
var txt = elem.html();
var len = opts.substr_len;
var dots = "<span>" + opts.ellipses + "</span>";
var charAtLen = txt.substr(len, 1);
while (len < txt.length && !/\s/.test(charAtLen)) {
len++;
charAtLen = txt.substr(len, 1);
}
var shown = txt.substring(0, len) + dots;
var hidden = '<span class="hidden" style="display:none;">' + txt.substring(len, txt.length) + '</span>';
elem.html(shown + hidden);
}
...and it will behave as you desire. You might want to add an option to turn this feature off and on, but I'll leave that up to you.
...它会按照您的意愿行事。您可能想要添加一个选项来关闭和打开此功能,但我会留给您。
回答by Edgar Villegas Alvarado
Instead of doing this:
而不是这样做:
$elem.readmore({
substr_len: 35
});
You could do this
你可以这样做
$elem.readmore({
substr_len: $elem.text().substr(0, 35).lastIndexOf(" ")
});
What we're doing is to go to the latest space posible before index 35. Of course 35 can be variable. Also you could put it into a function to reuse it.
我们正在做的是转到索引 35 之前可能的最新空间。当然 35 可以是可变的。你也可以把它放到一个函数中来重用它。
Hope this helps
希望这可以帮助
回答by user954728
I was just gathering information about this subject, with your help and the help from other related posts I wrote this:
我只是在收集有关此主题的信息,在您的帮助和其他相关帖子的帮助下,我写了以下内容: