jquery.ellipsis.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. (function($) {
  2. $.fn.ellipsis = function(options) {
  3. // default option
  4. var defaults = {
  5. 'row' : 1, // show rows
  6. 'onlyFullWords': false, // set to true to avoid cutting the text in the middle of a word
  7. 'char' : '...', // ellipsis
  8. 'callback': function() {}
  9. };
  10. options = $.extend(defaults, options);
  11. this.each(function() {
  12. // get element text
  13. var $this = $(this);
  14. var text = $this.text();
  15. var origHeight = $this.height();
  16. // get height
  17. $this.text('a');
  18. var lineHeight = parseFloat($this.css("lineHeight"), 10);
  19. var rowHeight = $this.height();
  20. var gapHeight = lineHeight > rowHeight ? (lineHeight - rowHeight) : 0;
  21. var targetHeight = gapHeight * (options.row - 1) + rowHeight * options.row;
  22. if (origHeight <= targetHeight) {
  23. $this.text(text);
  24. options.callback.call(this);
  25. return;
  26. }
  27. // Binary search for max length
  28. var start = 1;
  29. var end = text.length;
  30. while (start < end) {
  31. var length = Math.ceil((start + end) / 2);
  32. $this.text(text.slice(0, length) + options['char']);
  33. if ($this.height() <= targetHeight) {
  34. start = length;
  35. } else {
  36. end = length - 1;
  37. }
  38. }
  39. text = text.slice(0, start);
  40. if (options.onlyFullWords) {
  41. text = text.replace(/[\u00AD\w\uac00-\ud7af]+$/, ''); // remove fragment of the last word together with possible soft-hyphen characters
  42. }
  43. $this.text(text + options['char']);
  44. options.callback.call(this);
  45. });
  46. return this;
  47. };
  48. }) (jQuery);