使用场景:项目中需要计算文本的高度,如果超过两行,就折叠文本,显示展示全部按钮
使用span元素来计算,比较准确
//计算好准确的高度和宽度
textSize(fontSize, text) {
let span = document.createElement("span");
let result = {};
result.width = span.offsetWidth;
result.height = span.offsetHeight;
span.style.visibility = "hidden";
span.style.fontSize = fontSize;
span.style.lineHeight = '20px';//最好设置行高 方便项目中计算
span.style.fontFamily = '-apple-system, "PingFang SC", "Helvetica Neue", Helvetica,\n' +
'STHeiTi, sans-serif';//字体 可以替换为项目中自己的字体
span.style.display = "inline-block";
document.body.appendChild(span);
if (typeof span.textContent !== "undefined") {
span.textContent = text;
} else {
span.innerText = text;
}
result.width = parseFloat(window.getComputedStyle(span).width) - result.width;
result.height = parseFloat(window.getComputedStyle(span).height) - result.height;
span.parentNode.removeChild(span);//删除节点
return result;
}
更多内容,欢迎同步关注作者公众号二维码!
程序员内功修炼手册 主要发布计算机基础、设计模式、计算机网络基础知识,同时重点关注大前端知识
Android、iOS、web前端、Flutter、React Native等,想学习大前端知识的速度来吧,一起学习、一起成长!