JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div class="container"><span>测试test testa 测试test testab 测试test testabc 测试test testabcd 测试test</span></div>
</body>
CSS
.container {
text-align: left;
width: 300px;
background: gray;
font-size: 20px;
line-height: 24px;
}
JavaScript
let offCtx = null;
async function adjustFontSizeSingle(containerEle, minFontSize = 16, adjustLineHeight = false) {
let isOverflow = false;
const computedStyle = getComputedStyle(containerEle);
if (!/^\d+/.test(computedStyle.lineHeight)) {
throw new Error('container\'s lineHeight must be a exact value!');
}
let lineHeight = Number(computedStyle.lineHeight.slice(0, -2));
let fontSize = Number(computedStyle.fontSize.slice(0, -2));
if (isTextOverflow(1, containerEle)) {
isOverflow = true;
}
if (!isOverflow) {
return;
}
const textBody = containerEle.childNodes[0];
if (!offCtx) {
offCtx = document.createElement('canvas').getContext('2d');
}
const { fontFamily } = computedStyle;
this.offCtx.font = `${fontSize}px ${fontFamily}`;
const { width: measuredWidth } = this.offCtx.measureText(textBody.innerText);
if (containerEle.offsetWidth >= measuredWidth) {
return;
}
let firstTransFontSize = fontSize;
let firstTransLineHeight = lineHeight;
firstTransFontSize = Math.max(
minFontSize,
fontSize * (containerEle.offsetWidth / measuredWidth)
);
firstTransLineHeight = firstTransFontSize / fontSize * lineHeight;
fontSize = firstTransFontSize;
containerEle.style.fontSize = `${fontSize}px`;
if (adjustLineHeight) {
lineHeight = firstTransLineHeight;
containerEle.style.lineHeight = `${lineHeight}px`;
}
console.log('溢出调整完成');
}
document.addEventListener('DOMContentLoaded',function(){
adjustFontSizeSingle(document.querySelector('.container'));
});