You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现初始固定高度、点击自适应内容且可再次收缩的容器效果

容器点击展开/收缩实现方案

逻辑调整说明

你现有代码的逻辑是反向的:当前默认height为空(对应默认auto全高状态),点击后收缩为3rem。调整逻辑后即可实现初始小高度、点击自动适配内容展开的效果。

最简实现(无过渡动画)

如果不需要动画效果,直接切换高度属性即可,完全自动适配内容高度:

/* 基础样式,也可以写在CSS文件中 */
#hoisting {
  overflow: hidden;
  cursor: pointer;
}
const hoistingId = document.getElementById('hoisting')
// 初始化固定小高度
hoistingId.style.height = '3rem'

function enlargeBlogItem() {
  hoistingId.style.height = hoistingId.style.height === '3rem' ? 'auto' : '3rem'
}

hoistingId.addEventListener('click', enlargeBlogItem)

带过渡动画的实现(体验更优)

直接用height: auto无法触发CSS过渡,需要通过scrollHeight获取内容实际高度做中转,同时支持内容动态变化后的自动适配:

#hoisting {
  height: 3rem;
  overflow: hidden;
  cursor: pointer;
  /* 过渡时长和JS中超时时间保持一致 */
  transition: height 0.3s ease;
}
const hoistingId = document.getElementById('hoisting')

function enlargeBlogItem() {
  if (hoistingId.style.height === '' || hoistingId.style.height === '3rem') {
    // 展开逻辑:先设置为内容实际高度触发过渡
    hoistingId.style.height = `${hoistingId.scrollHeight}px`
    // 过渡结束后设为auto,后续内容变化自动适配高度
    setTimeout(() => {
      hoistingId.style.height = 'auto'
    }, 300)
  } else {
    // 收缩逻辑:先把auto转为实际高度,再触发收缩过渡
    hoistingId.style.height = `${hoistingId.scrollHeight}px`
    // 强制浏览器重绘,确保过渡生效
    void hoistingId.offsetHeight
    hoistingId.style.height = '3rem'
  }
}

hoistingId.addEventListener('click', enlargeBlogItem)

核心原理

  • element.scrollHeight可以拿到容器内容的实际总高度,不需要手动计算设置
  • 展开后设为height: auto,后续容器内文本、图片加载完成或者动态修改内容,高度都会自动适配,不需要额外监听调整

内容的提问来源于stack exchange,提问作者omno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:06:05