如何使用JavaScript实现文章超过两行时显示更多按钮
需求说明
实现当文章内容超过2行时显示「更多」按钮,若文章刚好为2行或不足2行则无需展示该按钮。
原实现问题
原方案采用固定字符长度判断是否截断,因不同字符(中文、英文、符号、空格)渲染宽度不一致,会导致判断不准确,出现内容不足2行显示按钮、或超出2行未显示按钮的异常。
功能说明图

修复后完整实现代码
HTML代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content"> 我是 james 我是文章 我是 james 我是文章 我是 james 我是文章 我 是 james 我是文章 我是 james 我是文章 </div>
CSS代码
.content{ width: 200px; font-size: 15px; line-height: 1.5; overflow:hidden; text-overflow:clip; display:-webkit-box; -webkit-box-orient:vertical; -webkit-line-clamp:2; } .info-more { border: none; background: transparent; color: #2d7ff9; cursor: pointer; padding: 0; margin-top: 6px; }
JS代码
$(function(){ // 计算2行文本对应的总高度 const lineHeight = parseFloat($('.content').css('line-height')); const maxAllowHeight = lineHeight * 2; $('.content').each(function(){ const $ele = $(this); // 临时取消溢出限制,获取内容实际高度 const originalOverflowVal = $ele.css('overflow'); $ele.css('overflow', 'visible'); const realContentHeight = $ele.height(); // 恢复原有样式 $ele.css('overflow', originalOverflowVal); // 高度超出2行才插入更多按钮 if(realContentHeight > maxAllowHeight) { $ele.after(`<button class='info-more'>...更多</button>`); // 点击展开全文逻辑,可根据需求调整 $(document).on('click', '.info-more', function(){ $(this).prev('.content').css('-webkit-line-clamp', 'unset'); $(this).remove(); }) } }); });
实现逻辑说明
- 不再按字符长度判断,而是通过计算内容实际渲染高度和2行总高度的差值判断是否需要显示按钮,适配所有字符类型的内容场景
- 点击按钮可直接放开行数限制展示全文,也可根据需求修改为跳转到详情页等其他逻辑
内容的提问来源于stack exchange,提问作者AWEI
相关产品推荐
相关产品推荐

