jQuery Plugin “readmore”, trim text without cuttin

2020-06-22 09:12发布

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.

I would love to avoid cutting words, how could I do that?

If the limit is 35, don't cut the 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.

3条回答
时光不老,我们不散
2楼-- · 2020-06-22 09:35

I was just gathering information about this subject, with your help and the help from other related posts I wrote this:

http://jsfiddle.net/KHd6J/526/

查看更多
小情绪 Triste *
3楼-- · 2020-06-22 09:37

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.

Hope this helps

查看更多
4楼-- · 2020-06-22 09:43

You can change the abridge function within that plugin as follows:

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.

See working example →

查看更多
登录 后发表回答