下拉菜单无法添加更多选项求助:overflow:hidden使用矛盾
解决下拉菜单选项数量受限的问题
问题很明显:你给展开后的菜单固定设置了200px高度,每个<li>有20px上下padding,5个选项加起来总高度早就超过200px了,overflow:hidden直接把超出的部分裁掉了。另外纠正个误区:移除项目符号是list-style-type: none的作用,和overflow:hidden没关系,不用因为这个纠结。
给你两个实用的修改方案:
方案一:用max-height代替height(推荐,保留过渡动画)
把固定的height换成max-height,设置一个足够大的最大值,不管加多少选项都能正常显示,同时过渡动画效果也能保留:
.slide { clear: both; width: 100%; max-height: 0px; /* 收起状态设为0 */ list-style-type: none; text-align: center; overflow: hidden; transition: max-height .4s ease; } .slide li {padding : 20px;} #touch {position: absolute; opacity: 0; height: 0;} #touch:checked + .slide {max-height: 500px; /* 设个足够大的值,比如500px,确保能装下所有选项 */}
方案二:JS动态计算高度(适合需要精确高度的场景)
如果不想用max-height,也可以用JS动态算出所有选项的总高度,再赋值给菜单元素,这样高度完全匹配:
<input type="checkbox" id="touch"> <ul class="slide" id="slideMenu"> <li><a href="#">Lorem Ipsum</a></li> <li><a href="#">Lorem Ipsum</a></li> <li><a href="#">Lorem Ipsum</a></li> <li><a href="#">Lorem Ipsum</a></li> <li><a href="#">Lorem Ipsum</a></li> </ul>
.slide { clear: both; width: 100%; height: 0px; list-style-type: none; text-align: center; overflow: hidden; transition: height .4s ease; } .slide li {padding : 20px;} #touch {position: absolute; opacity: 0; height: 0;}
const touchBtn = document.getElementById('touch'); const slideMenu = document.getElementById('slideMenu'); // 计算所有选项的总高度 function getTotalHeight() { let total = 0; slideMenu.querySelectorAll('li').forEach(item => { total += item.offsetHeight; }); return total; } // 监听复选框状态变化 touchBtn.addEventListener('change', function() { slideMenu.style.height = this.checked ? `${getTotalHeight()}px` : '0px'; });
这样改完,既能保留overflow:hidden实现展开收起的功能,所有添加的选项也都能显示,项目符号也不会出现。
内容的提问来源于stack exchange,提问作者Fatima
相关产品推荐
相关产品推荐

