使用 HTML、CSS 和 JS 创建侧边栏

2025-06-05

使用 HTML、CSS 和 JS 创建侧边栏

别废话了。我们开始吧:要创建一个简单的侧边栏,你需要解决 3 个主要任务:

  1. 创建适当的结构(HTML)
  2. 添加样式和位置(CSS)
  3. 添加打开/关闭行为(JS)

[文章末尾的 Codepen 链接]

那么,让我们从 HTML 开始吧。我们将创建一个固定在屏幕右侧的 div。我想补充一条我自己在编写中大型 HTML 时制定的规则:永远不要直接在“祖父”元素上添加或组织内容,这样可以避免麻烦。

<div id="sidebar1" class="sidebar">
  <div class="sidebar__content">
    <span>whatever you want</span>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

因为我们正在写一个侧边栏,所以可以只用一个 div 来实现,但正如我所说,这不利于扩展性。所以,我们将使用.sidebardiv 作为容器和.sidebar__content内容——嗯,呵呵 :P

如果您正在考虑可访问性(您应该考虑),您可能需要navaside标签,具体取决于您实现侧边栏的方式和位置。这也会改变元素role。由于我们正在进行非常基础的讨论,我建议您(如果您还不了解这些内容)向 Google 咨询有关 HTML 语义和可访问性的问题,以补充本教程。

我们将使用 aria 属性来管理侧边栏状态,如果您不了解 aria,可以从此链接开始:https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA

假设我在页面上添加了一个主侧边栏。因此,我们将使用 来aria-label命名主侧边栏,并aria-hidden使用 来管理其状态(可见或不可见)。

<div id="sidebar1" class="sidebar" aria-label="Main sidebar containing navigation links and some information" aria-hidden="true">
  <div class="sidebar__content">
    <span>whatever you want</span>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

现在我们已经有了结构。让我们添加样式。我们将使用 CSS 中的“aria-hidden”属性来决定侧边栏何时可见或不可见。但首先,让我们先来关注一下位置:

body {
  min-height: 100vh;
}
/* SIDEBAR POSITION */
.sidebar {
  background-color: #f1f1f1;
  height: 100vh;
  position: fixed;
  top: 0;
  right: 0;
  min-width: 300px;
}
.sidebar__content {
  padding: 8px;
  overflow-y: scroll;
  overflow-x: hidden;
}
Enter fullscreen mode Exit fullscreen mode

在 css 的“侧边栏位置”部分,我们告诉侧边栏固定在屏幕的右侧,并且保持屏幕高度作为其自身的高度,就像一个固定的支架一样。

然后我们确定内容将有一些填充,并且在需要时可以垂直滚动。

现在让我们显示/隐藏侧边栏。为此,我们需要将侧边栏平移(移动)到视口之外。由于侧边栏位于右侧,因此我们需要将其向右移动。侧边栏需要平移的最小必要距离是其自身宽度,或者说其本身宽度的 100%。

正如我所说,我们将使用aria-hidden作为状态管理器,因此规则很简单:当侧边栏有 时aria-hidden true,我们会将其向右平移 100%(即整个尺寸),使其移出视口。当侧边栏没有aria-hidden或有 时aria-hidden false,我们会移除平移,将侧边栏放回其原始位置:

/* SIDEBAR HIDDEN STATE */
.sidebar[aria-hidden="true"] {
  transition: 200ms;
  transform: translateX(100%);
}
/* SIDEBAR VISIBLE STATE */
.sidebar:not([aria-hidden]),
.sidebar[aria-hidden="false"] {
  transition: 200ms;
  transform: translateX(0);
}
Enter fullscreen mode Exit fullscreen mode

注意这条.sidebar:not([aria-hidden])规则。这意味着,无论aria-hidden falsearia-hidden 属性是否有效,侧边栏都会显示。因此,您可以使用 JS 脚本设置该属性的 true/false 或添加/移除该属性。无论如何,我们都会避免移除 aria 属性,因此我们将通过 JS 脚本设置 aria-hidden 属性的 true/false 来管理侧边栏的可见性。

我们将使用 JS 创建一个包含侧边栏 ID 的数据属性。我们将其命名为data-toggle-sidebar。具有此属性的元素将根据传入的侧边栏 ID 查询文档,然后——猜猜怎么着——通过更改 aria-hidden 的值 uu 来切换侧边栏。

以下是代码:

// Catch all the `[data-toggle-sidebar]` elements on the document.
document.querySelectorAll('[data-toggle-sidebar]').forEach(toggle => {
   // Add an event listener on those elements "click" event
   toggle.addEventListener('click', e => {
     // get the sidebar ID from the current element data attribute
     const sidebarID = toggle.dataset.toggleSidebar;
     // check if there is an element on the doc with the id
     const sidebarElement = sidebarID ? document.getElementById(sidebarID) : undefined;
     // if there is a sidebar with the passed id (data-toggle-sidebar)
     if (sidebarElement) {
        // toggle the aria-hidden state of the given sidebar
        let sidebarState = sidebarElement.getAttribute('aria-hidden');
        sidebarElement.setAttribute('aria-hidden', sidebarState == 'true' ? false : true); 
     }
   });
});
Enter fullscreen mode Exit fullscreen mode

通过上面注释的代码,您可以轻松了解 JS 代码的作用。简而言之:当data-toggle-sidebar点击某个元素时,我们将使用它的值作为 ID 在文档中搜索侧边栏。如果该元素(侧边栏)存在,它将反转其 aria-hidden 值,从而切换侧边栏的可见性 :)

让我们回到 HTML 代码,添加一个按钮来测试切换功能。
您必须按照以下示例添加按钮:

<div id="sidebar1" class="sidebar" aria-label="Main sidebar containing navigation links and some information" aria-hidden="true">
  <div class="sidebar__content">
    <span>whatever you want</span>
  </div>
</div>

<button data-toggle-sidebar="sidebar1" aria-label="Toggle the document main sidebar visibility">Toggle Sidebar</button>
Enter fullscreen mode Exit fullscreen mode

现在,您可以根据需要添加任意数量的侧边栏(当然,可以使用不同的 ID),并data-toggle-sidebar通过将侧边栏 ID 作为属性值传递来切换它们。侧边栏将在元素的点击事件时切换data-toggle-sidebar

最后,你必须得到这样的结果:

通过这里,您可以改进侧边栏,为可访问性问题添加更好的支持,在单击侧边栏时添加新功能,关心当我打开一个已经打开另一个侧边栏的新侧边栏时会发生什么,对 CSS 进行完全响应的方法等...这可以成为新研究的一个很酷的触发器。

封面图片由 Henry & Co. 在 Unsplash 上提供

就这些了,各位。

文章来源:https://dev.to/felipperegazio/creating-a-sidebar-with-html-css-and-js-1jep
PREV
CSS 自定义属性(vars)与 SASS/SCSS,一种实用的架构策略
NEXT
各位开发者,我们的姓氏该怎么写?我们目前的迭代 未来的可能性 Roygreen(更简单但仍然令人困惑) 关键要点 你的挑战