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
const callbacks = [];
let pending = false;
let timerFunc = null;
function flushCallbacks() {
pending = false;
const copies = callbacks.slice(0);
callbacks.length = 0;
for(let i = 0; i < copies.length; i += 1) {
copies[i]();
}
}
const p = Promise.resolve();
timerFunc = () => {
p.then(flushCallbacks);
setTimeout(() => {});
}
function nextTick(callback) {
let _resolve = null;
callbacks.push(() => {
if (callback) {
try {
callback()
} catch (e) {
console.warn('nextTick error: ', e);
}
} else if (_resolve) {
_resolve();
}
})
if (!pending) {
pending = true;
timerFunc();
}
if (!callback) {
return new Promise((resolve) => {
_resolve = resolve;
})
}
}
/**
*
* @param {Number} lineNum 限制最大允许的行数
* @param {*} containerEle 文本容器
* @param {*} minFontSize 限制最小可以缩小到的字号
* @returns
*/
function adjustFontSizeSingle(containerEle, minFontSize = 8) {
return new Promise(async (resolve) => {
const computedStyle = getComputedStyle(containerEle);
const needResetWhiteSpace = computedStyle.whiteSpace;
const needResetOverflow = computedStyle.overflow;
const fontSize = Number(computedStyle.fontSize.slice(0, -2));
// 设置文本不折行以计算文本总长度
containerEle.style.whiteSpace = 'nowrap';
containerEle.style.overflow = 'hidden';
await nextTick();
const textBody = containerEle.childNodes[0];
console.log(containerEle.offsetWidth, textBody.offsetWidth);
if (containerEle.offsetWidth < textBody.offsetWidth) {
// 按比例缩小字号到刚好占满容器
containerEle.style.fontSize = `${Math.max(
fontSize * (containerEle.offsetWidth / textBody.offsetWidth),
minFontSize
)}px`;
}
containerEle.style.whiteSpace = needResetWhiteSpace;
containerEle.style.overflow = needResetOverflow;
resolve();
...