javascript实现限定高度下文字随不同设备自适应改变字体大小至字数完全展示

复制代码
function fontAutoMoreLine() {
let textBox = document.getElementById("iconTxt");
let maxHeight = textBox.offsetHeight;
let title = document.getElementById("iconTitle");
let size = 5;
title.style.fontSize = size + 'vw';
let scrollHeight=title. scrollHeight;
while (title.scrollHeight > maxHeight) {
scrollHeight=title. scrollHeight;
//当容器高度大于最大高度的时候,上一个尝试的值就是最佳大小。
size = size - 0.2;
title.style.fontSize = size + 'vw';
if(scrollHeight<=title.scrollHeight){
$("#iconTitle").addClass("lineClamp");
break;
}
}
}
fontAutoMoreLine();
 
复制代码
<div class="iconTxt" id="iconTxt">
          <div class="iconTitle" id="iconTitle">
                   哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈
          </div>
</div>
复制代码
.iconTitle{font-weight:700;font-size:6vw;line-height: 8vw;}
.iconTxt{height:16vw;overflow: hidden;}
.lineClamp {
overflow: hidden !important;
text-overflow: ellipsis !important;
-webkit-line-clamp: 2;
display: -webkit-box;
-webkit-box-orient: vertical;
white-space: normal;
}
复制代码

效果如图:

 

单行文字自适应实现看这里

 

posted @   蓓蕾心晴  阅读(1474)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2017-10-25 Vue-router路由判断页面未登录跳转到登录页面
点击右上角即可分享
微信分享提示