需求:根据行数决定是否限制展开和收起。
思路:用2个块统计行高,一个不加高度限制用来统计行数(css隐藏),一个加高度限制用来显示(加高度限制会导致统计行数不准)要想知道文本的行数,那就需要知道文本的总高度和每一行的高度,总高度除以行高就是行数。当然总高度的计算必须是文字所在的 DOM 没有对高度的限制,随着文本的增加 DOM 要随之变高才行;最后还要考虑 DOM 的样式padding和margin对高度的影响。这样一来我们就可以计算出文本的行数了。总结一下我们需要如下几步:

克隆文本所在的 DOM;

清除 DOM 的高度限制;

获取 DOM 的行高和高度;

计算行数;

去除克隆的 DOM。
克隆文本所在的 DOM;清除 DOM 的高度限制;获取 DOM 的行高和高度;计算行数;去除克隆的 DOM。相关代码
document.getElementById("noticeContent").innerText = str;//展示的块

document.getElementById("noticeContent2").innerText = str;//计算行高的块



this.$nextTick(() => {

let noticeDom = document.getElementById("noticeContent2");

console.log(noticeDom);

let style = window.getComputedStyle(noticeDom, null);

let row = 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;

}

});

document.getElementById("noticeContent").innerText = str;//展示的块

document.getElementById("noticeContent2").innerText = str;//计算行高的块



this.$nextTick(() => {

let noticeDom = document.getElementById("noticeContent2");

console.log(noticeDom);

let style = window.getComputedStyle(noticeDom, null);

let row = 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;

}

});