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

如何通过JS切换div的col-sm-10/col-sm-12类实现响应式布局

实现侧边栏切换时动态调整内容区域的Bootstrap列类

嘿,这个需求很好实现,只需要给内容区域的div加个标识,再在你的侧边栏切换函数里添加上类名切换的逻辑就行,咱们一步步来:

1. 给内容区域div添加ID并设置初始类

首先修改HTML里的内容div,给它加一个唯一ID(方便JS定位),同时把初始类改成col-sm-12(符合页面加载时的要求):

<div class="row">
  <div class="col-sm-2">
    <div id="mySidenav" class="sidenav">
      <a href="javascript:void(0)" class="closebtn" onclick="closeNav()"><i class="fa fa-times-circle" style="font-size:16px;color:white"></i></a>
      <div class="menus">
        <a href="#">About</a>
        <a href="#">Services</a>
        <a href="#">Clients</a>
        <a href="#">Contact</a>
      </div>
    </div>
    <span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776;</span>
  </div>
  <!-- 这里添加id="contentDiv",初始类改为col-sm-12 -->
  <div id="contentDiv" class="col-sm-12">
    <table class="table">
      <tr>
        <th>Sr No.</th>
        <th>Title</th>
        <th>Name</th>
        <th>Picture</th>
        <th>Action</th>
        <th>Picture</th>
        <th>Action</th>
        <th>Picture</th>
        <th>Action</th>
        <th>Picture</th>
        <th>Action</th>
      </tr>
    </table>
  </div>
</div>

2. 修改JS函数,添加类名切换逻辑

接下来更新你的openNav()和closeNav()函数,在处理侧边栏宽度的同时,切换内容区域的列类。这里推荐用classList方法(比直接替换className更安全,不会覆盖div上的其他类名):

function openNav() {
  document.getElementById("mySidenav").style.width = "15%";
  // 获取内容区域元素
  const contentDiv = document.getElementById("contentDiv");
  // 移除col-sm-12,添加col-sm-10
  contentDiv.classList.remove("col-sm-12");
  contentDiv.classList.add("col-sm-10");
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
  const contentDiv = document.getElementById("contentDiv");
  // 移除col-sm-10,添加回col-sm-12
  contentDiv.classList.remove("col-sm-10");
  contentDiv.classList.add("col-sm-12");
}

如果你的内容div没有其他额外类名,也可以直接用className简化写法:

function openNav() {
  document.getElementById("mySidenav").style.width = "15%";
  document.getElementById("contentDiv").className = "col-sm-10";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
  document.getElementById("contentDiv").className = "col-sm-12";
}

这样修改后,页面加载时内容区域会占满12列,点击菜单按钮打开侧边栏时,内容区域自动切换为10列;关闭侧边栏时,又会恢复成12列,完全符合你的需求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:31:02