提问背景 Question:
内容如果不多的话,展开与收起就不用显示出来了吧。
<!-- 原始提问模块 -->
<div id="question-top"></div>
<div
class="bg-gray-50 border-l-4 border-blue-500 p-4 rounded-r-lg mb-6"
>
<div
class="text-xs font-bold text-blue-600 uppercase tracking-wider mb-1"
>
提问背景 Question:
</div>
<p
class="text-gray-700 font-medium text-sm md:text-base msg-wrapper">
<div id="content-body" class="msg-content" style="white-space: pre-wrap">
{{.Article.Question}}
</div>
<button onclick="toggleContent()">展开/收起</button>
</p>
</div>
function toggleContent() {
const anchor = document.getElementById('question-top');
const el = document.getElementById('content-body');
el.classList.toggle('expanded');
//window.location.hash = 'question-top';
anchor.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
原生JS实现智能文本折叠
这是一个非常经典且实用的交互痛点:如果内容本来就很少,根本不需要显示“展开/收起”按钮。只有当内容超过预设的高度(比如 150px 或 6 行以上)时,按钮才应该自动出现。
为了彻底摆脱外部框架依赖,这里使用纯原生 HTML + 极简 CSS + 智能 JS 来实现:
1. 完整代码(直接复制替换)
你可以直接将下面这段结构替换到你现有的模板中,无需引入任何第三方 JS 或 CSS CDN:
<!-- 锚点:用于收起后精确定位到顶部 -->
<div id=