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

效果如圖:

 

單行文字自適應實現看這里

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM