简体   繁体   中英

jQuery Plugin “readmore”, trim text without cutting words

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.

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

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 →

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM