You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript检测.entry-title元素溢出并动态缩小字体?

检测.entry-title内容溢出并动态缩小字体大小

核心逻辑

通过对比元素的scrollWidth(内容实际宽度)和clientWidth(元素可见宽度)判断是否溢出:当scrollWidth > clientWidth时,说明内容超出了容器范围,此时动态调整字体大小并重置溢出相关样式。

实现代码

先保留你的初始CSS配置:

.entry-title {
  font-size: 1.42em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

再添加以下JavaScript代码:

// 获取所有带.entry-title类的元素
const titleElements = document.querySelectorAll('.entry-title');

// 逐个检测并处理
titleElements.forEach(title => {
  // 判断是否发生内容溢出
  if (title.scrollWidth > title.clientWidth) {
    // 缩小字体至原大小的95%
    title.style.fontSize = 'calc(1.42em * 0.95)';
    // 重置溢出相关样式
    title.style.whiteSpace = 'inherit';
    title.style.overflow = 'inherit';
    title.style.textOverflow = 'inherit';
  }
});

窗口适配补充

如果需要在窗口尺寸变化(比如缩放浏览器、调整窗口大小)时重新检测,可把逻辑封装成函数并绑定到resize事件:

function checkTitleOverflow() {
  const titleElements = document.querySelectorAll('.entry-title');
  titleElements.forEach(title => {
    // 先重置样式,避免之前的调整干扰新的检测结果
    title.style.fontSize = '';
    title.style.whiteSpace = '';
    title.style.overflow = '';
    title.style.textOverflow = '';

    if (title.scrollWidth > title.clientWidth) {
      title.style.fontSize = 'calc(1.42em * 0.95)';
      title.style.whiteSpace = 'inherit';
      title.style.overflow = 'inherit';
      title.style.textOverflow = 'inherit';
    }
  });
}

// 页面加载完成后执行一次
document.addEventListener('DOMContentLoaded', checkTitleOverflow);
// 窗口大小变化时重新检测
window.addEventListener('resize', checkTitleOverflow);

内容的提问来源于stack exchange,提问作者volker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:41:02