本文介绍一种轻量级 javascript 方案,用于实时检测 `.entry-title` 元素是否发生文本溢出,并在触发时自动缩小字体、恢复换行与溢出样式,兼顾多行文本兼容性与性能。
在响应式网页开发中,仅依赖 @media 查询(如按视口宽度缩放字体)虽简单高效,但无法应对内容长度动态变化的场景——例如用户编辑标题、CMS 后台生成不同长度标题、或同一页面多个 .entry-title 元素因父容器宽度差异而产生不一致溢出行为。此时,需借助 JavaScript 实现精准的“内容驱动型”字体适配。
以下是一个健壮、可复用的检测逻辑(支持单行与多行文本):
function adjustFontSizeToFit(element, options = {}) {
const {
minFontSize = 0.8, // 最小缩放比例(相对于初始 font-size)
step = 0.05, // 每次缩放步长
maxAttempts = 20, // 防止无限循环的最大尝试次数
restoreStyles = true // 是否还原 white-space/overflow 等样式(设为 false 可保留 ellipsis)
} = options;
const originalStyle = {
fontSize: window.getComputedStyle(element).fontSize,
whiteSpace: element.style.whiteSpace,
overflow: element.style.overflow,
textOverflow: element.style.textOverflow
};
// 保存初始 fontSize(转为 px 值便于计算)
const originalPx = parseFloat(originalStyle.fontSize);
let currentSize = originalPx;
let attempts = 0;
// 检测是否溢出:对比 scrollWidth > clientWidth(单行)或 scrollHeight > clientHeight(多行)
const isOverflowing = () => {
return element.scrollWidth > element.clientWidth ||
element.scrollHeight > element.clientHeight;
};
// 循环缩小字体直至不溢出或达到最小值
while (isOverflowing() && currentSize > originalPx * minFontSize
&& attempts < maxAttempts) {
currentSize -= originalPx * step;
element.style.fontSize = `${currentSize}px`;
attempts++;
}
// 可选:还原原始溢出控制样式(如需保留省略号则跳过)
if (restoreStyles) {
element.style.whiteSpace = 'inherit';
element.style.overflow = 'inherit';
element.style.textOverflow = 'inherit';
}
}
// 使用示例:为所有 .entry-title 元素启用自适应
document.querySelectorAll('.entry-title').forEach(el => {
// 初始调用
adjustFontSizeToFit(el, { minFontSize: 0.7, step: 0.03 });
// 可选:监听窗口 resize(防布局变动后再次溢出)
const resizeObserver = new ResizeObserver(() => {
// 重置为原始字体再重新适配(避免残留过小字号)
el.style.fontSize = '';
adjustFontSizeToFit(el, { minFontSize: 0.7, step: 0.03 });
});
resizeObserver.observe(el);
});✅ 关键优势说明:
⚠️ 注意事项:
总结:相比纯 CSS 媒体查询,该方案以极小的 JS 开销实现了“内容真实适配”,特别适合 CMS、卡片列表、仪表盘标题等动态文本场景。它不是替代响应式设计,而是对其的重要补充——让字体真正“读懂内容”。