Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo off-canvas menu với CSS và JavaScript

Dưới đây là code để tạo off-canvas menu:

Ví dụ

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <style>
    .sideNav {
      height: 100vh;
      width: 0;
      position: fixed;
      z-index: 1;
      top: 0;
      left: 0;
      background-color: rgb(46, 218, 195);
      overflow-x: hidden;
      padding-top: 60px;
      transition: 0.5s;
    }
    .sideNav a {
      padding: 8px 8px 8px 32px;
      text-decoration: none;
      font-size: 25px;
      color: #000000;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      display: block;
      transition: 0.3s;
    }
    .sidenav a:hover {
      color: #f1f1f1;
    }
    .sideNav .closeBtn {
      position: absolute;
      top: 0;
      right: 25px;
      font-size: 36px;
      margin-left: 50px;
    }
    button {
      padding: 15px;
      background-color: rgb(0, 27, 145);
      color: rgb(255, 255, 255);
      font-size: 20px;
      border: none;
      border-radius: 2%;
    }
    .main-content{
      transition: 0.5s;
    }
  </style>
</head>
<body>
  <nav class="sideNav">
    <a href="#" class="closeBtn">×</a>
    <a href="#">Login</a>
    <a href="#">Register</a>
    <a href="#">Home</a>
    <a href="#">About Us</a>
  </nav>
  <main class="main-content">
    <button class="openSideNav">Click here to open sideNav</button>
    <h1>Here is some sample text</h1>
    <p>Here is some random sample text too</p>
  </main>
  <script>
    let openBtn = document.querySelector(".openSideNav");
    openBtn.addEventListener("click", () => {
      showNav();
    });
    let closeBtn = document.querySelector(".closeBtn");
    closeBtn.addEventListener("click", () => {
      hideNav();
    });
    function showNav() {
      document.querySelector(".sideNav").style.width = "300px";
      document.querySelector('.main-content').style.marginLeft = "300px";
    }
    function hideNav() {
      document.querySelector(".sideNav").style.width = "0";
      document.querySelector('.main-content').style.marginLeft = "0px";
    }
  </script>
</body>
</html>

Kết quả

Code này cho kết quả:

Tạo off-canvas menu với CSS và JavaScript

Khi click nút open side nav, navbar trượt từ trái và đẩy content chính:

Tạo off-canvas menu với CSS và JavaScript