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

beileixinqing 2018-10-25 03:56 原文

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;
}

效果如图:

 

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

 

推荐阅读