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

基于W3.CSS创建侧边栏触发自适应调整的固定顶部导航栏

使用W3.CSS实现适配侧边栏的固定顶部导航栏

我帮你完善并整理了实现代码,完美实现固定顶部导航栏,且当侧边栏展开时能自动调整尺寸适配空间。下面是完整可运行的示例:

<!DOCTYPE html>
<html>
<head>
  <title>W3.CSS Fixed Navbar with Sidebar</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <style>
    /* 可选:自定义导航栏样式,添加平滑过渡效果 */
    .w3-top {
      z-index: 100;
      transition: margin-left 0.3s ease;
    }
  </style>
</head>
<body>

<!-- 固定顶部导航栏 -->
<div class="w3-top w3-blue" id="myNavbar">
  <button class="w3-button w3-blue w3-xlarge" onclick="toggleSidebar()">
    <i class="fa fa-bars"></i>
  </button>
  <div class="w3-center w3-padding-large">顶部导航栏</div>
</div>

<!-- 侧边栏 -->
<div class="w3-sidebar w3-bar-block w3-gray w3-animate-left" style="width:25%;display:none" id="mySidebar">
  <button class="w3-bar-item w3-button w3-large" onclick="toggleSidebar()">关闭 &times;</button>
  <a href="#" class="w3-bar-item w3-button">菜单项1</a>
  <a href="#" class="w3-bar-item w3-button">菜单项2</a>
  <a href="#" class="w3-bar-item w3-button">菜单项3</a>
</div>

<!-- 主内容区域 -->
<div class="w3-main" style="margin-top:80px;padding:20px">
  <h2>主内容区域</h2>
  <p>点击左上角按钮展开/收起侧边栏,导航栏会自动调整尺寸适配空间</p>
</div>

<script>
function toggleSidebar() {
  const sidebar = document.getElementById("mySidebar");
  const navbar = document.getElementById("myNavbar");
  
  // 切换侧边栏显示状态,同步调整导航栏位置
  if (sidebar.style.display === "block") {
    sidebar.style.display = "none";
    navbar.classList.remove("w3-margin-left-25");
  } else {
    sidebar.style.display = "block";
    navbar.classList.add("w3-margin-left-25");
  }
}
</script>

</body>
</html>

关键特性说明:

  • 固定顶部导航栏:通过w3-top类实现导航栏固定在页面顶部,不会随页面滚动位移。
  • 侧边栏自适应:点击按钮触发函数,通过给导航栏添加/移除w3-margin-left-25类(对应侧边栏25%的宽度),让导航栏自动让出侧边栏的空间,实现尺寸自适应。
  • 流畅交互:给导航栏添加过渡动画,让尺寸变化更自然;侧边栏使用w3-animate-left类实现展开/收起的滑动效果。
  • 灵活定制:你可以根据需求调整侧边栏宽度(比如改成30%,对应w3-margin-left-30类),或者修改导航栏、侧边栏的颜色、样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:01:19