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

如何实现仅当内容高度超42px时显示Show more/Show less链接

实现仅当内容高度超过指定值时显示「Show more/Show less」链接

要解决单行内容仍显示切换链接的问题,我们需要通过JavaScript判断内容的真实高度,再决定是否显示链接,具体实现如下:

1. 优化HTML(可选,便于元素选择)

给切换链接添加类名,方便后续JS精准选择:

<div class="container">
        <div class="row justify-content-center">
          <div class="col-md-4">
            <div id="summary">
              <p class="collapse" id="collapseSummary">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porttitor maximus laoreet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In hac habitasse platea dictumst. Suspendisse venenatis sollicitudin erat in gravida. Sed eget nisl tristique, commodo lectus sit amet, vulputate sem. Cras porttitor lorem ipsum, sit amet iaculis massa feugiat vitae. Curabitur sapien odio, ullamcorper tincidunt interdum vitae, vestibulum eu neque. Nam leo massa, fringilla eget mauris feugiat, auctor suscipit justo.
              </p>
              <a class="collapsed toggle-link" data-toggle="collapse" href="#collapseSummary" aria-expanded="false" aria-controls="collapseSummary"></a>
            </div></div></div>

2. 添加JavaScript判断逻辑

通过JS计算内容真实高度,与指定阈值(42px)对比,控制链接的显示隐藏,同时监听窗口尺寸变化,确保布局改变时重新判断:

// 获取目标元素
const contentPara = document.getElementById('collapseSummary');
const toggleLink = document.querySelector('.toggle-link');
const threshold = 42; // 设定的高度阈值

// 判断是否显示切换链接的核心函数
function toggleLinkDisplay() {
  // 临时移除高度限制,获取内容真实高度
  contentPara.style.height = 'auto';
  const realHeight = contentPara.offsetHeight;
  // 恢复原有样式
  contentPara.style.height = '';

  // 根据高度对比结果控制链接显示
  if (realHeight > threshold) {
    toggleLink.style.display = 'inline';
  } else {
    toggleLink.style.display = 'none';
    // 内容高度不足时直接展开(可选操作)
    contentPara.classList.add('show');
  }
}

// 页面加载完成后执行一次判断
window.addEventListener('load', toggleLinkDisplay);
// 窗口尺寸变化时重新判断,适配响应式布局
window.addEventListener('resize', toggleLinkDisplay);

3. 调整CSS(可选,优化初始状态)

给切换链接添加初始隐藏样式,避免页面加载时短暂出现不必要的链接:

#summary .toggle-link {
  display: none;
}

原理说明

  • 临时移除段落的高度限制,获取其未被截断时的真实高度
  • 将真实高度与设定的42px阈值对比,决定是否显示切换链接
  • 监听窗口resize事件,确保窗口尺寸变化时重新计算高度,避免布局变化导致判断失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:51:39