/** * 多行缩略 兼容 * @author rubekid * { * maxLine:2, //最多显示行默认为1 * ellipsisChar:"..." //省略占位符,建议不设置,与原生一致 * } */ (function ($) { var supportLineClamp = function(){ var div = document.createElement('div'); var style = computeStyle(div); return style!=null && "-webkit-line-clamp" in style; }(); function computeStyle(el){ if(window.getComputedStyle){ return window.getComputedStyle(el,null); } return el.currentStyle; } /** * 设置样式 * @param Element el * @param JSON css */ function setStyle(el, css){ for(var i in css){ el.style[i] = css[i]; } } function ellipsis($elem, options) { var maxLine = options.maxLine ||1; var lineHeight = parseFloat($elem.css("line-height")); var maxHeight = maxLine * lineHeight; var content = $elem.text(); var $temp_elem = $elem.clone(false) .css({"visibility": "hidden","overflow":"visible", "height":"auto"}) .appendTo($elem.parent()); $temp_elem.text(content); var height = $temp_elem.height(); if(height > maxHeight){ if(supportLineClamp){ setStyle($elem.get(0), { "text-overflow":"ellipsis", "display":"-webkit-box", "-webkit-line-clamp":maxLine, "-webkit-box-orient":"vertical", "overflow":"hidden" }); } else{ var _width = $elem.width(); var ellipsis_char = options.ellipsisChar; var lineCount = 0; var texts = content.split("\n", maxLine); var newTexts = []; for(var i=0; i= maxLine){ text = text + ellipsis_char; $temp_elem.text(text); text = text.replace(' ',' '); //for fix white-space bug  $temp_elem.css({"whiteSpace": "nowrap","width":"auto" }); var max = (maxLine - lineCount) * _width; var width = $temp_elem.get(0).scrollWidth; if(width > max){ var stop = Math.floor(text.length * max / width); // for performance while content exceeding the limit substantially var temp_str = text.substring(0,stop) + ellipsis_char; width = $temp_elem.text(temp_str).get(0).scrollWidth; if(width > max){ while (width > max && stop > 1) { stop--; temp_str = text.substring(0, stop) + ellipsis_char; width = $temp_elem.text(temp_str).width(); } } else if(width < max){ while (width < max && stop < text.length) { stop++; temp_str = text.substring(0, stop) + ellipsis_char; width = $temp_elem.text(temp_str).get(0).scrollWidth; } if(width > max){ temp_str = text.substring(0,stop -1)+ellipsis_char; } } newTexts.push(temp_str.replace(' ',' ')); } else{ newTexts.push(text); } break; } newTexts.push(text); lineCount +=_lineCount; } text = newTexts.join("\n"); $temp_elem.text(text).css( {"whiteSpace": "","width": $elem.width() } ); var lastIndex = text.length; var _temp_str = text; height = $temp_elem.height(); while(height > maxHeight){ _temp_str = text.substring(0, --lastIndex) + ellipsis_char; $temp_elem.text(_temp_str); height = $temp_elem.height(); } $elem.text(_temp_str); } } $temp_elem.remove(); } var defaults = { maxLine: 1, ellipsisChar:'...' }; $.fn.ellipsis = function (options) { return this.each(function () { var $elem = $(this); var opts = $.extend({}, defaults, options); ellipsis($elem, opts); }); }; $.fn.ellipsis.options = defaults; })(jQuery);