多行内容超出显示的JS解决方案
一个貌似很简单,但写起来也不简单的问题对于多行文字,超出。。。显示。
通过css可以实现,但受限于浏览器兼容问题,有时候还需要依赖js来实现。
通过js实现,就需要考虑到文字大小,中英文、数字、标点符号所对应的字节长度不一致,如果考虑的不全面,对于不同的文字内容,总会有点差距。
首先,我们需要了解,中文汉字,英文字母,数字以及特殊符号所占的字节长度是不一样的,如果需要计算准确,就不能按照字符串的元素个数去截取,把它们换算成字节数来截取,准确度更高。所以,我们需要一个获取字符串字节长度的方法:functionbitCompute(content){vartotal0,lenarguments〔0〕。length0for(vari0;ilen;i){if(content〔i〕。charCodeAt()255){total2;}else{total1;}}returntotal}
对于要截取多少内容的字节数,我们需要知悉能放入容器内的字节数与总字节数的比例,展示字节数总字节数offsetWidthscrollWidth:functioncomplate(){varoffsetWidthel。offsetWidth;varscrollWidthel。scrollWidth;vargapscrollWidthoffsetWidth;varpercentMath。floor(offsetWidthscrollWidth1e3)1e3;return{gap:gap,percent:percent}}
根据计算得出的数据,我们就可以操作字符串了。functioncut(content){el。innerhtmlcontent;varinfocomplate(),percentinfo。percent;vartotalbitCompute(content)。total;varshowLen(totalpercent)。toFixed(0)cfg。placeholder;contentbitCompute(content,showLen)。content;returncontentcfg。padding;}functionbitCompute(content,maxLen){vartotal0,lenarguments〔0〕。length0,outContent;for(vari0;ilen;i){if(content〔i〕。charCodeAt()255){total2;}else{total1;}if(maxLentotalmaxLen){break;}outContentcontent〔i〕;}return{total:total,content:outContent}}
当然文字展示的多少,也是和字体大小相关的,所以我们也需要把字体大小的因素考虑到,而且作为一个工作方法,本身就不应该页面中的元素有关联,所以我们应该在方法中自己创建元素,放入内容,计算offsetWidth和scrollWidth。functioncutFactory(opt){varcfg{padding:opt。padding。。。,classList:opt。classList〔〕,style:opt。style{},debug:opt。debug};cfg。placeholderbitCompute(cfg。padding)。total;vareldoc。createElement(span);el。classNamecfg。classList。join();varcustomStyles〔〕;for(varstyleKeyincfg。style){if(cfg。style。hasOwnProperty(styleKey)){customStyles。push(styleKey:cfg。style〔styleKey〕);}}el。style。cssTextposition:absolute;left:0;top:0;background:transparent;color:transparent;height:100;whitespace:nowrap;overflow:visible;border:0;(cfg。debug?background:white;color:red;:)customStyles。join(;);varpdoc。createElement(p);p。appendChild(el);p。style。cssTextwidth:99;minheight:50px;lineheight:50px;position:absolute;left:3px;top:3px;overflow:hidden;outline:0;background:transparent;(cfg。debug?outline:1pxsolidred;background:black;:);doc。body。appendChild(p);varcsswin。getComputedStyle(el);cfg。fontSizeparseFloat(css。fontSize)16;returnfunction(content){el。innerhtmlcontent;varout{flag:false,cut:,all:content,last:content}if(complate()。gap0){out。flagtrue,out。lastout。cutcut(content)}returnout}}
最后,再暴露一个方法,方便使用者调用。
为了性能考虑,不创建过多dom元素,我们可以缓存一下字体大小和容器宽度相同的截取方法。functionsubStringEL(name,fontSize,width){this。subStringELFns(this。subStringELFns{});varkeykeyfontSizewidth;varfnthis。subStringELFns〔key〕;if(!fn){fnthis。subStringELFns〔key〕cutFactory({style:{fontsize:fontSize,width:width}})}returnfn(name);}
这样就完美的解决了多行超出。。。显示的问题了,兼容性很好,而且也能准确截取,灵活方便。