JSFiddle - React, Tailwind, and code Playground

by superyngo

HTML

<body>
    <nav>
      <ul class="nav">
        <li><a class="nav-button" href="#">首頁</a></li>
        <li><a class="nav-button" href="#">全部商品</a></li>
        <li><a class="nav-button" href="#">全部品牌</a></li>
        <li>
          <a href="#" class="nav-button">關於我們</a>
          <ul class="dropdownMenu">
            <li>
              <a href="#">團隊介紹</a>
            </li>
            <li>
              <a href="#">企業宗旨</a>
            </li>
            <li>
              <a href="#">創業故事</a>
            </li>
          </ul>
        </li>
      </ul>
    </nav>
  </body>

CSS

*,
*::before,
*::after {
  box-sizing: border-box;
}

* {
  margin: 0;
  padding: 0;
  font: inherited;
  list-style: none;
}

body {
  min-height: 100vh;
}

ul.nav {
  display: flex;
  height: 50px;
  justify-content: center;
  align-items: center;
  gap: 2px;
  background-color: #faebd7;
}

ul.nav li {
  background-color: rgb(243, 176, 93);
  /* border: 2px solid black; */
  min-width: 100px;
  text-align: center;
  box-shadow: 0 2px 3px 0 black;
  position: relative;
}

a:hover {
  color: aqua;
}

ul.dropdownMenu {
  position: absolute;
  top: 25px;
  display: none;
}

ul.dropdownMenu.show {
  display: block;
}

JavaScript

let dropdownMenus = document.querySelectorAll(".dropdownMenu");
window.onclick = function () {
  let target = event.target;
  if (target.matches(".nav-button") && target.nextElementSibling != null) {
    target.nextElementSibling.classList.toggle("show");
  } else {
    for (let dropdownMenu of dropdownMenus) {
      dropdownMenu.classList.remove("show");
    }
  }
};