实现Show More/Show Less功能:动态内容超5行时折叠
实现动态内容的多行截断与展开/收起功能
第一步:修改CSS添加截断样式和展开状态
更新你的CSS,为描述文本添加line-clamp截断样式,同时定义展开后的显示状态:
.description-container { display: flex; flex-direction: column; /* 改为垂直排列,让按钮在文本下方 */ align-items: center; margin-top: 1rem; } .description { margin-top: 1rem; padding: 1rem; width: 70rem; background-color: #333; border-radius: 0.5rem; } .description p { margin: 0; font-size: 1rem; line-height: 1.5; /* 多行截断核心样式 */ display: -webkit-box; -webkit-line-clamp: 5; -webkit-box-orient: vertical; overflow: hidden; transition: all 0.3s ease; } /* 展开状态的样式 */ .description p.expanded { -webkit-line-clamp: unset; overflow: visible; } .showMoreLess { margin-top: 0.5rem; color: #4299e1; cursor: pointer; font-size: 0.9rem; display: none; /* 默认隐藏按钮,仅内容超5行时显示 */ }
第二步:添加JavaScript逻辑处理交互与显示判断
在页面加载完成后,加入以下JS代码,判断内容高度并处理按钮切换:
document.addEventListener('DOMContentLoaded', function() { const descContainer = document.querySelector('.description-container'); const descText = descContainer.querySelector('.description p'); const toggleBtn = descContainer.querySelector('.showMoreLess'); // 计算5行文本的预期高度:行高 × 5 const lineHeight = parseFloat(getComputedStyle(descText).lineHeight); const maxHeight = lineHeight * 5; // 检查内容是否超出5行,是则显示按钮 if (descText.scrollHeight > maxHeight) { toggleBtn.style.display = 'inline-block'; } // 按钮点击切换逻辑 toggleBtn.addEventListener('click', function() { descText.classList.toggle('expanded'); this.textContent = descText.classList.contains('expanded') ? 'Show Less' : 'Show More'; }); });
针对Svelte环境的简化方案
因为你的HTML使用了{@html data.description},看起来是Svelte项目,可直接用组件语法简化逻辑:
<script> let data = { description: '' }; // 你的动态数据 let isExpanded = false; let showToggle = false; // 数据更新后自动检查内容高度 $: if (data.description) { const descText = document.querySelector('.description p'); const lineHeight = parseFloat(getComputedStyle(descText).lineHeight); const maxHeight = lineHeight * 5; showToggle = descText.scrollHeight > maxHeight; } </script> <div class="description-container"> <div class="description"> <p class:expanded={isExpanded}>{@html data.description}</p> </div> {#if showToggle} <span class="showMoreLess" on:click={() => isExpanded = !isExpanded}> {isExpanded ? 'Show Less' : 'Show More'} </span> {/if} </div> <style> /* 放入之前的CSS样式 */ </style>
关键细节说明
line-clamp是webkit内核属性,现代主流浏览器均支持,若需兼容旧浏览器,可改用JS计算高度的方案,但line-clamp是最简洁的实现方式。- 将
.description-container的flex-direction改为column,让按钮自然位于文本下方,符合用户浏览习惯。 - 按钮默认隐藏,仅当内容实际超出5行时才显示,避免内容不足时出现冗余元素。
内容的提问来源于stack exchange,提问作者HiroBeBroke
相关产品推荐
相关产品推荐

