当前位置: 首页 > Web前端 > vue.js

JavaScript如何计算文本行数

时间:2023-03-31 20:13:32 vue.js

需求:根据行数判断是否限制展开和折叠。思路:用2块统计行高,一块不限高统计行(csshidden),一块限高显示(加限高会导致行数不准)知道文本行号的行数,然后你需要知道文字的总高度和每行的高度,总高度除以行高就是行数。当然,总高度的计算必须是文本所在的DOM没有高度限制。随着文本的增加,DOM必须变高;最后,还要考虑DOM样式的padding和margin对高度的影响。这样我们就可以计算文本的行数。综上所述,我们需要以下步骤:克隆文本所在的DOM;清除DOM的高度限制;获取DOM的行高和高度;计算行数;删除克隆的DOM。相关代码document.getElementById("noticeContent").innerText=str;//显示的块document.getElementById("noticeContent2").innerText=str;//计算行高的块this.$nextTick(()=>{letnoticeDom=document.getElementById("noticeContent2");console.log(noticeDom);letstyle=window.getComputedStyle(noticeDom,null);letrow=Math.ceil(Number(style.height.replace("px",""))/Number(style.lineHeight.replace("px","")));//总行高/每行高度console.log("noticeDom===>",style.height,style.lineHeight);console.log("rowwwww",row);if(row>2){//如果显示超过2行,展开收起this.showOmit=true;this.showOpen=true;}else{this.showOpen=false;}});