以下是一个基本的 HTML 代码,其中右侧有一个可伸缩的目录栏:

<!DOCTYPE html>
<html>
<head>
  <style>
    /* 设置目录栏的样式 */
    .sidebar {
      position: fixed;
      top: 0;
      right: 0;
      width: 200px;
      height: 100%;
      background-color: #f0f0f0;
      overflow-y: auto; /* 允许滚动 */
      transition: width 0.3s ease; /* 添加过渡效果 */
    }

    /* 设置目录栏的伸缩按钮样式 */
    .toggle-button {
      position: absolute;
      top: 10px;
      right: 10px;
      width: 20px;
      height: 20px;
      background-color: #ccc;
      cursor: pointer;
      transition: background-color 0.3s ease; /* 添加过渡效果 */
    }

    /* 设置目录栏的内容样式 */
    .sidebar-content {
      padding: 20px;
    }

    /* 设置目录栏伸缩按钮的hover效果 */
    .toggle-button:hover {
      background-color: #999;
    }

    /* 给目录栏添加伸缩效果 */
    .collapsed .sidebar {
      width: 0;
    }

    .collapsed .toggle-button {
      right: 0;
    }
  </style>
</head>
<body>
  <div class='sidebar'>
    <div class='toggle-button' onclick='toggleSidebar()'></div>
    <div class='sidebar-content'>
      <!-- 在这里添加目录栏的内容 -->
      <h2>目录</h2>
      <ul>
        <li>章节1</li>
        <li>章节2</li>
        <li>章节3</li>
      </ul>
    </div>
  </div>

  <!-- 在这里添加其他页面内容 -->

  <script>
    function toggleSidebar() {
      var sidebar = document.querySelector('.sidebar');
      sidebar.classList.toggle('collapsed');
    }
  </script>
</body>
</html>

在这个代码中,我们使用了 CSS 来设置目录栏的样式。通过给目录栏的外部容器添加position: fixed样式,将其固定在右侧。然后使用overflow-y: auto样式来允许内容溢出时出现滚动条。通过添加过渡效果,我们可以实现目录栏的伸缩。最后,通过 JavaScript 中的toggleSidebar函数,我们可以在点击伸缩按钮时切换目录栏的伸缩状态。

HTML 代码实现右侧可伸缩目录栏

原文地址: https://www.cveoy.top/t/topic/qqL7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录