这是我创建的最优雅的解决方案。它使用二进制搜索,进行 10 次迭代。天真的方法是做一个while循环并将字体大小增加1,直到元素开始溢出。您可以使用 element.offsetHeight 和 element.scrollHeight 确定元素何时开始溢出。如果 scrollHeight 比 offsetHeight 大,你的字体太大了。
二分搜索是一个更好的算法。它还受到您要执行的迭代次数的限制。只需调用 flexFont 并插入 div id,它就会在 8px 和 96px 之间调整字体大小。
我花了一些时间研究这个主题并尝试不同的库,但最终我认为这是最简单、最直接的解决方案。
请注意,如果您愿意,可以更改为使用offsetWidth 和scrollWidth,或将两者都添加到此函数中。
// Set the font size using overflow property and div height
function flexFont(divId) {
var content = document.getElementById(divId);
content.style.fontSize = determineMaxFontSize(content, 8, 96, 10, 0) + "px";
};
// Use binary search to determine font size
function determineMaxFontSize(content, min, max, iterations, lastSizeNotTooBig) {
if (iterations === 0) {
return lastSizeNotTooBig;
}
var obj = fontSizeTooBig(content, min, lastSizeNotTooBig);
// if `min` too big {....min.....max.....}
// search between (avg(min, lastSizeTooSmall)), min)
// if `min` too small, search between (avg(min,max), max)
// keep track of iterations, and the last font size that was not too big
if (obj.tooBig) {
(lastSizeTooSmall === -1) ?
determineMaxFontSize(content, min / 2, min, iterations - 1, obj.lastSizeNotTooBig, lastSizeTooSmall) :
determineMaxFontSize(content, (min + lastSizeTooSmall) / 2, min, iterations - 1, obj.lastSizeNotTooBig, lastSizeTooSmall);
} else {
determineMaxFontSize(content, (min + max) / 2, max, iterations - 1, obj.lastSizeNotTooBig, min);
}
}
// determine if fontSize is too big based on scrollHeight and offsetHeight,
// keep track of last value that did not overflow
function fontSizeTooBig(content, fontSize, lastSizeNotTooBig) {
content.style.fontSize = fontSize + "px";
var tooBig = content.scrollHeight > content.offsetHeight;
return {
tooBig: tooBig,
lastSizeNotTooBig: tooBig ? lastSizeNotTooBig : fontSize
};
}