如何不使用jQuery根据内容最多的标签页设置HTML标签页高度?
纯原生HTML/CSS/JS实现标签页高度自适应 tallest 内容面板
完全可以用纯原生代码实现这个需求,不需要任何框架。下面是一个完整的可直接复用的示例,适配你的LMS场景:
HTML结构
<div class="tab-container"> <!-- 标签按钮组 --> <div class="tab-buttons"> <button class="tab-btn active" data-tab="tab1">标签1</button> <button class="tab-btn" data-tab="tab2">标签2</button> <button class="tab-btn" data-tab="tab3">标签3</button> </div> <!-- 内容容器 --> <div class="tab-content-wrapper"> <div class="tab-content active" id="tab1"> <p>这是标签1的内容,比较短。</p> </div> <div class="tab-content" id="tab2"> <p>这是标签2的内容,内容比较长。</p> <p>多添加几行文本,用来测试高度自适应效果。</p> <p>再多加一行,确保这个标签的高度是最大的。</p> <p>继续加,让高度更明显。</p> </div> <div class="tab-content" id="tab3"> <p>标签3的内容长度中等。</p> <p>第二行文本。</p> </div> </div> </div>
CSS样式
.tab-container { width: 100%; max-width: 800px; margin: 20px 0; border: 1px solid #eee; border-radius: 4px; overflow: hidden; } .tab-buttons { display: flex; background-color: #f5f5f5; } .tab-btn { padding: 10px 20px; border: none; background: transparent; cursor: pointer; font-size: 14px; border-bottom: 2px solid transparent; } .tab-btn.active { border-bottom-color: #007bff; background-color: #fff; font-weight: bold; } .tab-content-wrapper { position: relative; background-color: #fff; min-height: 100px; /* 初始占位高度 */ } .tab-content { position: absolute; top: 0; left: 0; width: 100%; padding: 20px; box-sizing: border-box; display: none; } .tab-content.active { display: block; }
JavaScript逻辑
document.addEventListener('DOMContentLoaded', function() { const tabButtons = document.querySelectorAll('.tab-btn'); const tabContents = document.querySelectorAll('.tab-content'); const contentWrapper = document.querySelector('.tab-content-wrapper'); // 计算并设置容器高度为最高标签内容的高度 function setTabContainerHeight() { let maxHeight = 0; tabContents.forEach(content => { // 临时显示所有内容以获取真实高度 content.style.display = 'block'; const contentHeight = content.scrollHeight; if (contentHeight > maxHeight) { maxHeight = contentHeight; } // 恢复隐藏状态(除了激活的标签) if (!content.classList.contains('active')) { content.style.display = 'none'; } }); // 设置容器高度 contentWrapper.style.height = `${maxHeight}px`; } // 标签切换逻辑 tabButtons.forEach(button => { button.addEventListener('click', function() { // 移除所有激活状态 tabButtons.forEach(btn => btn.classList.remove('active')); tabContents.forEach(content => content.classList.remove('active')); // 添加当前标签的激活状态 this.classList.add('active'); const targetTab = document.getElementById(this.dataset.tab); targetTab.classList.add('active'); }); }); // 初始化时设置高度 setTabContainerHeight(); // 窗口 resize 时重新计算高度 window.addEventListener('resize', setTabContainerHeight); });
关键逻辑说明
- 高度计算核心:通过临时显示所有标签内容,获取每个内容的
scrollHeight(包含内边距的真实内容高度),取最大值设置给内容容器,确保所有标签内容都能完整显示。 - 标签切换:仅修改标签的显示状态,容器高度保持最大值,避免切换时出现高度跳动。
- 自适应窗口:监听窗口 resize 事件,确保窗口大小变化时重新计算高度,保持布局稳定。
如果你的标签内容是动态加载的,可在内容加载完成后再次调用setTabContainerHeight()更新高度。
内容的提问来源于stack exchange,提问作者Andy Connor
相关产品推荐
相关产品推荐

