如何动态设置div的max-height以仅显示单个列表项?
解决方案
要实现只显示第一个列表项并动态适配高度,可以通过获取折叠区域内需要显示的元素高度总和来设置max-height,替代静态值,具体步骤如下:
1. 调整CSS样式
保留基础的溢出隐藏和省略号样式,同时优化折叠状态下的显示逻辑:
.colonnes-texte.hide-text { overflow: hidden; } .colonnes-texte.hide-text .texte { /* 这里的max-height会由JS动态设置 */ transition: max-height 0.3s ease; /* 可选:添加展开收起过渡动画 */ } .colonnes-texte .texte.ellipsis-text ul li:first-child { list-style-position: inside; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* 展开时移除高度限制 */ .colonnes-texte.show-text .texte { max-height: none !important; }
2. 编写动态计算高度的JS逻辑
通过获取前置<p>和第一个<li>的高度总和,作为折叠时的max-height,同时绑定按钮的展开/收起切换事件:
const showTextButtons = document.querySelectorAll(".read-more"); const textContainers = document.querySelectorAll(".colonnes-texte"); // 初始化折叠状态并计算适配高度 textContainers.forEach(container => { const texte = container.querySelector(".texte"); const introPara = texte.querySelector("p"); const firstLi = texte.querySelector("ul li:first-child"); // 计算需要显示的元素高度总和(加10px余量避免内容截断) const collapseHeight = introPara.offsetHeight + firstLi.offsetHeight + 10; // 给容器设置动态计算的折叠高度 texte.style.maxHeight = `${collapseHeight}px`; container.classList.add("hide-text"); texte.classList.add("ellipsis-text"); }); // 绑定按钮点击事件,切换展开/收起状态 showTextButtons.forEach((button, index) => { button.addEventListener("click", () => { const container = textContainers[index]; const texte = container.querySelector(".texte"); if (container.classList.contains("hide-text")) { // 展开全文 container.classList.remove("hide-text"); container.classList.add("show-text"); button.textContent = "收起"; } else { // 折叠回初始状态 container.classList.remove("show-text"); container.classList.add("hide-text"); button.textContent = "Lire la suite"; } }); });
3. 关键逻辑说明
- 动态高度适配:用
offsetHeight获取元素实际渲染高度,总和值作为折叠高度,完美适配不同设备的字体大小、行高变化。 - 精准省略号控制:仅给第一个
<li>设置省略号样式,其他列表项被容器的overflow: hidden隐藏,符合需求。 - 交互优化:添加过渡动画让展开收起更流畅,按钮文本同步切换,提升用户体验。
这种方案避开了iOS上line-clamp对<ul>无效的问题,也解决了静态max-height适配性差的痛点。
内容的提问来源于stack exchange,提问作者trainee
相关产品推荐
相关产品推荐

