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

响应式导航菜单在Chrome等主流浏览器失效,求解决方法

响应式导航菜单无法触发移动端视图的修复方案

核心问题:缺少视口元标签

移动端浏览器默认会将页面宽度渲染为980px左右并缩放显示,导致你的max-width:768px媒体查询无法被触发,始终显示桌面布局。必须在HTML的<head>中添加视口元标签,让浏览器使用设备的实际宽度来渲染页面。

修复步骤

  1. 在HTML的<head>部分添加以下标签:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
  1. 可选优化:确保菜单切换按钮在桌面端隐藏,避免冗余显示
    在CSS的桌面样式中添加:
.menu-toggle {
  display: none;
}

然后在媒体查询中覆盖为显示:

@media only screen and (max-width: 768px) {
  .menu-toggle {
    display: block;
  }
  /* 其他现有样式... */
}

修改后的完整代码

HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Maxin Solutions</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
  <nav>
    <div class="logo">Maxin Solutions</div>
    <div class="menu-toggle" onclick="toggleMenu()">&#9776;</div>
    <ul class="menu" id="menu">
        <li><a href="/home">首页</a></li>
        <li><a href="/about">关于我们</a></li>
    </ul>
  </nav>
</header>
<script src="script.js"></script>
</body>
</html>

CSS

/* 响应式导航样式 */

nav {
  background-color: #fff;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  font-weight: bold;
}

.menu {
  display: flex;
  list-style: none;
}

.menu li {
  margin-right: 20px;
}

.menu li a {
  text-decoration: none;
  color: #333;
}

.menu-toggle {
  cursor: pointer;
  font-size: 20px;
  display: none; /* 桌面端隐藏切换按钮 */
}

/* 媒体查询 */

@media only screen and (max-width: 768px) {
  .menu {
    display: none;
  }

  .menu-toggle {
    display: block; /* 移动端显示切换按钮 */
  }

  #menu.open {
    display: flex;
    flex-direction: column;
    position: absolute;
    top: 60px;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 20px;
  }
  
  #menu.open li {
    margin-right: 0;
    margin-bottom: 10px;
  }
}

JavaScript

function toggleMenu() {
  var menu = document.getElementById("menu");
  menu.classList.toggle("open");
}

// 点击菜单项时关闭菜单(可选功能)
var menuItems = document.querySelectorAll(".menu li a");
for (var i = 0; i < menuItems.length; i++) {
  menuItems[i].addEventListener("click", function() {
    var menu = document.getElementById("menu");
    menu.classList.remove("open");
  });
}

额外检查点

  • 确认媒体查询语法无拼写错误:@media only screen and (max-width:768px)
  • 通过浏览器开发者工具查看元素样式,确认媒体查询样式未被其他CSS规则覆盖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:25:23