互联网技术 · 2024年2月11日

JavaScript实现计算文本行数的方法

这篇文章主要介绍了JavaScript 如何计算文本的行数的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

需求:根据行数决定是否限制展开和收起。

JavaScript 如何计算文本的行数的实现

思路:用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 计算文本行数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:脚本之家

链接:https://www.jb51.net/article/195571.htm

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册