본문 바로가기
Javascript/GMA(2302~)

23.04.17 오른쪽 사이드 메뉴 만들어보기

by hyerin1201 2023. 4. 17.

 

 

HTML

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script defer src="/script_5.js"></script>
  <link rel="stylesheet" href="/style_5.css">
  <title>Document</title>
</head>
<body>
  <button id="btn">&#9776;</button>
  <nav id="nav">
    <ul>
      <li><a href="#">HTML5</a></li>
      <li><a href="#">CSS3</a></li>
      <li><a href="#">JAVASCRIPT</a></li>
    </ul>
  </nav>
</body>
</html>

 

CSS

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0;
}
button {
  position: fixed;
  top: 20px;
  right: 20px;
  border: none;
  outline: none;

  background-color: #639;
  color: #fff;
  padding: 15px;
  transition: transform 0.3s ease-in-out;
}
nav {
  position: fixed;
  top: 0;
  right: 0;
  background-color: #639;
  height: 100vh;
  padding: 2em;
  transform: translateX(100%);
  /* display: none; */
  transition: transform 0.3s ease-in-out;
}
ul {
  padding: 0;
  margin: 0;
  list-style: none;
}
ul li {
  padding: 1em 0;
}
ul li a {
  text-decoration: none;
  color: #fff;
}
button.active {
  transform: translateX(-125px);
}
nav.active {
  transform: translateX(0);
}

 

Javascript

const btn = document.querySelector("#btn");
const nav = document.querySelector("#nav");

btn.addEventListener("click", () => {
  nav.classList.toggle("active");
  btn.classList.toggle("active");
})

자바스크립트 코드는 간단하다.

클래스 값을 없애고 생성할 수 있는 토글 기능사용하였고

클래스 값에는 위치값을 조절하였다.