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

如何仅用原生JavaScript实现Div的展开与收起(无需jQuery)

原生JavaScript实现Div展开收起(替代jQuery slideToggle效果)

对应HTML结构

<button id="button">-</button>
<div id="box">
  示例内容区域,点击按钮可展开/收起
</div>

CSS样式(实现滑动过渡效果)

#box {
  overflow: hidden;
  max-height: 0;
  transition: max-height 0.3s ease-out;
  padding: 0 10px;
  border: 1px solid #ccc;
}

#box.active {
  padding: 10px;
}

原生JavaScript实现代码

const toggleBtn = document.getElementById('button');
const contentBox = document.getElementById('box');

toggleBtn.addEventListener('click', function() {
  // 切换按钮文本
  this.textContent = this.textContent === '-' ? '+' : '-';
  
  const isExpanded = contentBox.classList.contains('active');
  
  if (isExpanded) {
    // 收起逻辑:先设置当前内容高度,再过渡到0
    contentBox.style.maxHeight = contentBox.scrollHeight + 'px';
    setTimeout(() => {
      contentBox.style.maxHeight = '0';
    }, 10);
    contentBox.classList.remove('active');
  } else {
    // 展开逻辑:设置为内容实际高度,触发过渡
    contentBox.style.maxHeight = contentBox.scrollHeight + 'px';
    contentBox.classList.add('active');
  }
  
  // 过渡结束后重置max-height,适配内容动态变化
  contentBox.addEventListener('transitionend', () => {
    if (!contentBox.classList.contains('active')) {
      contentBox.style.maxHeight = '';
    }
  }, { once: true });
});

说明

这段代码完全用原生JS实现了和你提供的jQuery示例一致的效果:

  • 点击按钮切换文本(-/+)
  • 通过CSS过渡模拟jQuery的slideToggle()滑动展开/收起效果
  • 动态计算内容高度,适配不同长度的内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:10:50