开发人员在编写汉堡菜单时犯的错误 许多汉堡菜单存在的问题 解决方案 结论

2025-05-28

开发人员在编写汉堡菜单时犯的错误

许多汉堡菜单的问题

解决方案

结论

《纽约时报》的开发人员对汉堡菜单的理解有哪些错误,而迪士尼和维基百科的开发人员又理解哪些正确呢?

据我所知,我只找到了一种支持 iOS Safari 的汉堡菜单打开状态样式。(大概是想让移动视图在 iPhone 上也能正常工作吧!)

这一切都取决于汉堡菜单的定位方式。

许多汉堡菜单的问题

如果您的汉堡菜单不需要滚动……恭喜!您现在想到的 CSS 解决方案可能就很好用:当用户点击菜单图标时,将侧边栏完全置于视口之外和之内。

如果您的菜单项数量超出了视口一次可以显示的范围,那么当您的汉堡菜单绝对定位时就会发生这种情况:

如果您不想看视频,我会尝试用文字来描述它。

注意到 iOS 有时候会滚动菜单,有时候会滚动菜单后面的主体吗?真让人抓狂!

顺便说一句,你也可以在Apple.com上关闭滚动功能。触发汉堡菜单滚动的一个简单方法是将手机横屏使用。

解决方案

基本上,关于菜单最终打开状态,你必须记住的关键一点是:菜单的定位不是绝对的,而是侧边栏打开后,主要内容的定位。换句话说,不是菜单的定位,而是其他所有内容的定位

以下是代码,以及解释性注释:

<html>
<head></head>
<body>
  <div class="sidebar">Hamburger menu links go here</div>
  <div class="main-content"><button class="hamburger-menu-icon" onClick="toggleSidebar()">🍔</button></div>
</body>
</html>
/* Arbitrary CSS variable values for explanatory purposes */
:root {
  --sidebar-width: 100px;
  --sidebar-bg-colour: blue;
}

.sidebar {
  display: none;
  position: relative;
  width: var(--sidebar-width);
}

@media (max-width: 767px) {
  html.sidebar-is-open .sidebar {
    display: block; 
     /* 
      The sidebar is just rendered in default position,
      as it appears in the document flow
     */
  }

  html.sidebar-is-open .main-content {
    position: fixed; 
    /* 
     It is the main content that is positioned. 
     This is the crux of the implementation. The rest is all sugar.

     Cons: the body will scroll to the top, losing your user's scroll position
    */

    /* prevents resizing from its original full-screen width */
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
    width: 100%; 

    overflow: hidden;
  }

  /* Optional enhancement: 
     make the overscroll on iPhone the same colour as the sidebar */
  html.sidebar-is-open body {
    background-color: var(--sidebar-bg-colour);
  }
  .sidebar {
    background-color: var(--sidebar-bg-colour);
  }
}
const documentElement = document.querySelector("html");
const contentElement = document.querySelector(".main-content");
const sidebarElement = document.querySelector(".sidebar");
const sidebarIsOpen = () => documentElement.classList.contains("sidebar-is-open");

const openSidebar = () => {
  /* How you trigger the change is up to you */
  documentElement.classList.add("sidebar-is-open");
};

const closeSidebar = () => {
  documentElement.classList.remove("sidebar-is-open");
};

const toggleSidebar = () => {
  sidebarIsOpen() ? closeSidebar() : openSidebar();
};

结论

到目前为止,我发现有两个大公司做得不错:维基百科迪士尼美国

在 iOS 上尝试他们的汉堡菜单,看看滚动的体验有多么棒!

希望您能传播这个消息,并从现在开始修复汉堡菜单。

(附注:或许我们可以干脆把它们作为 UI 解决方案全部移除,毕竟它还没困扰到足够多的人,不值得修复。现在还有人在用这些东西吗?考虑用标签栏,看看spotify 的 例子

如果您是初学者,您可以在我的博客上找到有关汉堡菜单是什么以及如何从头开始构建汉堡菜单的解释。

文章来源:https://dev.to/tongrhj/the-mistake-developers-make-when-coding-a-hamburger-menu-1deg
PREV
作为新开发者,如何摆脱教程的困境
NEXT
10 个能让你成为更优秀开发人员的项目和技能