提问背景 Question:
我真的很不喜欢被动的引用别人的这些东西的。
(index):64 cdn.tailwindcss.com should not be used in production. To use Tailwind CSS in production, install it as a PostCSS plugin or use the Tailwind CLI: https://tailwindcss.com/docs/installation
纯原生CSS与锚点跳转方案
这个警告是因为你在生产环境直接引入了 Tailwind 的 play.cdn。它在浏览器端动态解析 CSS,不仅性能极差、会产生这个警告,还让你不得不依赖外部的 CDN 服务器。
既然你不喜欢被动引用别人的东西,最直接、最清爽的办法就是彻底删掉 Tailwind CDN 引入,直接写纯原生 HTML + CSS。原生 CSS 没有任何依赖,加载极快,而且完全受你控制。
下面是使用纯原生代码加**HTML锚点(Anchor)**实现的“展开/收起并自动回到顶部”的完整方案:
1. 极简 HTML 结构
在提问容器的最顶部放一个隐形的锚点标签(例如 id="question-top"),然后把按钮的 href 指向它。
<!-- 1. 锚点定位点(放在提问内容的顶部) -->
<div id="question-top"></div>
<div class="msg-wrapper">
<!-- 2. 内容区域,默认是折叠状态 collapsed -->
<div id="msg-content" class="msg-content collapsed">
这里是上百行的超长提问内容... <br>
这里是上百行的超长提问内容... <br>
这里是上百行的超长提问内容...
</div>
<!-- 3. 控制按钮 -->
<div class="btn-container">
<button id="toggle-btn" onclick="toggleText()">展开全部</button>
</div>
</div>
2. 纯原生 CSS(写在本地 <style> 标签中)
无需任何外部库,利用原生 CSS 控制高度和过渡动画:
/* 容器样式 */
.msg-wrapper {
border: 1px solid #e2e8f0;
padding: 16px;
border-radius: 8px;
background: #f8fafc;
}
/* 文本区域:默认折叠状态 */
.msg-content {
overflow: hidden;
transition: max-height 0.3s ease-out; /* 平滑过渡效果 */
}
/* 折叠时的最大高度 */
.msg-content.collapsed {
max-height: 120px; /* 大约5行的高度 */
}
/* 展开时的最大高度(给一个足够大的安全值) */
.msg-content.expanded {
max-height: 5000px;
}
/* 按钮居中及样式 */
.btn-container {
display: flex;
justify-content: center;
margin-top: 12px;
}
#toggle-btn {
padding: 6px 16px;
background-color: #3b82f6;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
#toggle-btn:hover {
background-color: #2563eb;
}
3. 极简 JS 逻辑(锚点跳转)
当用户点击“收起”时,使用原生 JS 修改 window.location.hash 瞬间定位到锚点位置,或者使用 scrollIntoView 实现平滑滚动。
function toggleText() {
const content = document.getElementById('msg-content');
const btn = document.getElementById('toggle-btn');
const anchor = document.getElementById('question-top');
if (content.classList.contains('collapsed')) {
// 执行:展开
content.classList.remove('collapsed');
content.classList.add('expanded');
btn.textContent = '收起内容';
} else {
// 执行:收起
content.classList.remove('expanded');
content.classList.add('collapsed');
btn.textContent = '展开全部';
// 核心:收起后,页面瞬间定位到提问的顶部锚点
// 方式 A(最简单的标准锚点跳转,瞬间定位):
window.location.hash = 'question-top';
// 方式 B(如果你想要平滑滚动回去,用这行代替方式A):
// anchor.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}
为什么这个方案更好?
- 没有 CDN 警告:去掉了
cdn.tailwindcss.com,控制台瞬间干净。 - 完全自主掌控:所有样式和逻辑都在你本地的 HTML/CSS 文件中,不依赖任何第三方。
- 精准定位:收起时通过
#question-top锚点直接让浏览器视口回到提问起点,不会再发生“找不到当前位置”的迷茫感。