需求:根据行数决定是否限制展开和收起。
思路:用2个块统计行高,一个不加高度限制用来统计行数(css隐藏),一个加高度限制用来显示(加高度限制会导致统计行数不准)
要想知道文本得行数,那就需要知道文本得总高度和每一行得高度,总高度除以行高就是行数。当然总高度得计算必须是文字所在得 DOM 没有对高度得限制,随着文本得增加 DOM 要随之变高才行;最后还要考虑 DOM 得样式padding和margin对高度得影响。这样一来我们就可以计算出文本得行数了。总结一下我们需要如下几步:
- 克隆文本所在得 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; } });
到此这篇关于JavaScript 如何计算文本得行数得实现得内容就介绍到这了,更多相关JavaScript 计算文本行数内容请搜索来客网以前得内容或继续浏览下面得相关内容希望大家以后多多支持来客网!