UNPKG

text-clamp

Version:

处理文字超出最大行数显示...

6 lines 2.6 kB
/*! * text-clamp v1.0.1 * (c) 2017-2018 penyuying * Released under the MIT License. */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.clamp={})}(this,function(e){"use strict";e.clamp=function(e,t){function n(e,t){return c.getComputedStyle||(c.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return"float"==t&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle&&e.currentStyle[t]?e.currentStyle[t]:null},this}),c.getComputedStyle(e,null).getPropertyValue(t)}function i(t){var n=t||e.clientHeight,i=l(e);return Math.max(Math.floor(n/i),0)}function l(e){var t=n(e,"line-height");return"normal"==t&&(t=1.2*parseInt(n(e,"font-size"))),parseInt(t)}function a(t){return t.lastChild.children&&t.lastChild.children.length>0?a(Array.prototype.slice.call(t.children).pop()):t.lastChild&&t.lastChild.nodeValue&&""!=t.lastChild.nodeValue&&t.lastChild.nodeValue!=s.truncationChar?t.lastChild:(t.lastChild.parentNode.removeChild(t.lastChild),a(e))}function r(t,n){if(n){var i=t.nodeValue.replace(s.truncationChar,"");if(m||(g=y.length>0?y.shift():"",m=i.split(g)),m.length>1?(v=m.pop(),o(t,m.join(g))):m=null,u&&(t.nodeValue=t.nodeValue.replace(s.truncationChar,""),e.innerHTML=t.nodeValue+" "+u.innerHTML+s.truncationChar),m){if(e.clientHeight<=n){if(!(y.length>=0&&""!=g))return e.innerHTML;o(t,m.join(g)+g+v),m=null}}else""==g&&(o(t,""),t=a(e),y=s.splitOnChars.slice(0),g=y[0],m=null,v=null);if(!s.animate)return r(t,n);setTimeout(function(){r(t,n)},!0===s.animate?10:s.animate)}}function o(e,t){e.nodeValue=t+s.truncationChar}t=t||{};var u,c=window,s={clamp:t.clamp||2,useNativeClamp:void 0===t.useNativeClamp||t.useNativeClamp,splitOnChars:t.splitOnChars||[".","-","\u2013","\u2014"," "],animate:t.animate||!1,truncationChar:t.truncationChar||"\u2026",truncationHTML:t.truncationHTML},p=e.style,d=e.innerHTML,h=void 0!==e.style.webkitLineClamp,f=s.clamp,C=f.indexOf&&(f.indexOf("px")>-1||f.indexOf("em")>-1);s.truncationHTML&&((u=document.createElement("span")).innerHTML=s.truncationHTML);var m,v,y=s.splitOnChars.slice(0),g=y[0];"auto"==f?f=i():C&&(f=i(parseInt(f)));var x;if(h&&s.useNativeClamp)p.overflow="hidden",p.textOverflow="ellipsis",p.webkitBoxOrient="vertical",p.display="-webkit-box",p.webkitLineClamp=f,C&&(p.height=s.clamp+"px");else{var H=function(t){return l(e)*t}(f);H<=e.clientHeight&&(x=r(a(e),H))}return{original:d,clamped:x}},Object.defineProperty(e,"__esModule",{value:!0})});