当前位置: 首页 > 后端技术 > PHP

多行内容超...展示的终极解决方法

时间:2023-03-29 13:42:07 PHP

最近遇到一个看似简单的问题,写起来却不容易。对于多行文本,显示beyond...。可以通过css实现,但是受限于浏览器兼容性问题,有时需要依赖JS来实现。通过js实现,需要考虑文字的大小。中英文、数字、标点符号对应的字节长度不一致。如果考虑不全面,不同的文本内容总会有差距。首先我们要明白,汉字、英文字母、数字、特殊符号所占用的字节长度是不一样的。如果计算需要精确,我们不能根据字符串中的元素个数进行截取,并转换成字节。截取个数,准确率更高。所以,我们需要一个方法来获取字符串的字节长度:functionbitCompute(content){vartotal=0,len=arguments[0].length||0for(vari=0;i255){total+=2;}else{总计+=1;}}returntotal}复制代码对于要截取的内容的字节数,我们需要知道可以放入容器中的字节数占总字节数的比例,显示字节数/总字节数=offsetWidth/scrollWidth:functioncomplate(){varoffsetWidth=el.offsetWidth;varscrollWidth=el.scrollWidth;vargap=scrollWidth-offsetWidth;varpercent=Math.floor(offsetWidth/scrollWidth*1e3)/1e3;return{gap:gap,percent:percent}}复制代码根据计算出的数据,我们可以操作字符串函数cut(content){el.innerHTML=content;varinfo=complate(),percent=info.percent;vartotal=bitCompute(content).total;varshowLen=+(总计*百分比).toFixed(0)-cfg.占位符;content=bitCompute(content,showLen).content;返回内容+cfg.padding;}functionbitCompute(content,maxLen){vartotal=0,len=arguments[0].length||0,outContent='';对于(vari=0;i255){total+=2;}else{总计+=1;}if(maxLen&&total>maxLen){中断;}outContent+=内容[i];}return{total:total,content:outContent}}复制代码当然显示的文字量也和字号有关,所以我们也需要考虑字号的因素,作为工作方法,应该和页面本身的元素没有关系,所以我们应该在方法中自己创建元素,放入内容,计算offsetWidth和scrollWidthfunctioncutFactory(opt){varcfg={padding:opt.padding||“...”,类列表:opt.classList||[],样式:opt.style||{},调试:opt.debug};cfg.placeholder=bitCompute(cfg.padding).total;varel=doc.createElement("span");el.className=cfg.classList.join("");varcustomStyles=[];for(varstyleKeyincfg.style){if(cfg.style.hasOwnProperty(styleKey)){customStyles.push(styleKey+":"+cfg.style[styleKey]);}}el.style.cssText="position:absolute;left:0;top:0;background:transparent;color:transparent;height:100%;white-space:nowrap;overflow:visible;border:0;"+(cfg.debug?"background:white;color:red;":"")+customStyles.join(";");vardiv=doc.createElement("div");div.appendChild(el);div.style.cssText="width:99%;min-height:50px;line-height:50px;position:absolute;left:3px;top:3px;overflow:hidden;outline:0;background:transparent;"+(cfg.debug?"outline:1pxsolidred;background:black;":"");doc.body.appendChild(div);varcss=win.getComputedStyle(el);cfg.fontSize=parseFloat(css.fontSize)||16;返回函数(内容){el。innerHTML=内容;varout={flag:false,cut:'',all:content,last:content}if(complate().gap>0){out.flag=true,out.last=out.cut=cut(content)}returnout}}复制代码最后再暴露一个方法,方便用户调用。出于性能考虑,在不创建过多dom元素的情况下,我们可以缓存字体大小和容器宽度同拦截方法functionsubStringEL(name,fontSize,width){this.subStringELFns||(this.subStringELFns={});varkey='key_'+fontSize+'_'+width;varfn=this.subStringELFns[key];if(!fn){fn=this.subStringELFns[key]=cutFactory({style:{'font-size':fontSize,'width':width}})}returnfn(name);}最后if如果你认为这篇文章对你有点帮助,点个赞吧。或者可以加入我的开发交流群:1025263163互相学习,我们会有专业的技术解答。如果您觉得这篇文章对您有用,请给我们的开源项目一个小星星:https://gitee。com/ZhongBangKe...非常感谢!PHP学习手册:https://doc.crmeb.com技术交流论坛:https://q.crmeb.com