如何实现默认展示3行无截断动态内容 点击Show More按钮展开全部
现有方案问题梳理
- 固定max-height没有考虑不同元素的高度差异,很容易截断半行文字或者半截标签
- 点击时设置max-height为
initial属于关键字赋值,无法触发CSS过渡动画,动效会失效
优化实现方案
核心思路:通过JS动态计算容器实际总高度和默认展示高度,保证默认展示的内容都是完整元素,不会出现截断,同时保留平滑过渡效果。
HTML 代码
和原有结构基本一致,调整了容器类名更语义化:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content-wrapper"> <p>hi, this is a test description.</p> <h2>hi, this is a test description.</h2> <p>hi, this is a test description.</p> <p>hi, this is a test description.</p> <h2>hi, this is a test description.</h2> </div> <a href="javascript:void(0)" class="show-btn">Show More</a>
CSS 代码
移除固定max-height,保留过渡配置:
.content-wrapper { overflow: hidden; transition: max-height 1s ease; margin-bottom: 0; font-size: 13px; line-height: 25px; } .show-btn.hidden { display: none; }
JS 代码
动态高度计算逻辑:
$(function() { const $wrapper = $('.content-wrapper'); const $btn = $('.show-btn'); // 对应你设置的行高值,可根据实际需求调整 const baseLineHeight = 25; // 默认最少展示3行的基础高度 const minShowHeight = baseLineHeight * 3; // 先获取容器完整内容的总高度 $wrapper.css('max-height', 'unset'); const fullHeight = $wrapper.outerHeight(); // 计算默认折叠高度:累加子元素高度,直到超过最小展示高度,保证不会截断任何子元素 let defaultHeight = 0; $wrapper.children().each(function() { const childHeight = $(this).outerHeight(true); if (defaultHeight >= minShowHeight) return false; defaultHeight += childHeight; }); // 如果内容总高度小于等于默认展示高度,自动隐藏展开按钮 if (fullHeight <= defaultHeight) { $btn.addClass('hidden'); } // 设置默认折叠状态的高度 $wrapper.css('max-height', defaultHeight + 'px'); // 展开/收起交互逻辑 let isExpanded = false; $btn.on('click', function() { if (isExpanded) { $wrapper.css('max-height', defaultHeight + 'px'); $btn.text('Show More'); } else { $wrapper.css('max-height', fullHeight + 'px'); $btn.text('Show Less'); } isExpanded = !isExpanded; }); });
方案特性
- 默认状态完整展示所有不超过3行基础高度的子元素,不会出现半截标签、半行文字的截断问题
- 展开和收起都有平滑的过渡动画
- 内容本身不足3行时自动隐藏展开按钮,不会出现多余操作入口
- 兼容任意内部元素,标题、段落、行内元素、自定义组件都能正常适配
内容的提问来源于stack exchange,提问作者Zain
相关产品推荐
相关产品推荐

