토글 버튼 구현하기!

22271 단어 TILpracticeTIL

구현된 화면


코드

HTML

  <nav class="container">
    <div class="logo">
      <i class="fas fa-apple-alt"></i>
      <div><a href="">Apeachicetea</a></div>
    </div>
  
    <ul class="menu">
      <li><a href="">Home</a></li>
      <li><a href="">Gallary</a></li>
      <li><a href="">Weddings</a></li>
      <li><a href="">FAQ</a></li>
      <li class="menu__last"><a href="">Bookings</a></li>
    </ul>

    <ul class="icons">
      <li><a href=""><i class="fab fa-instagram"></i></a></li>
      <li><a href=""><i class="fab fa-facebook-square"></i></a></li>
    </ul>

    <div class="toggle__btn"><a href="#"><i class="fas fa-bars"></i></a></div>

  </nav>

CSS

* {
  box-sizing: border-box;
}

body {
  margin: 0;
}

a {
  text-decoration: none;
  color: white;
}

li {
  list-style: none;
}

.container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  background-color: brown;
  padding: 15px 30px;
}

.logo {
  display: flex;
  align-items: center;
  font-size: 40px;
  color: white;
}

.logo i {
  padding-right: 10px;
}

.menu {
  display: flex;
  font-size: 30px;
}

.menu li {
  padding: 15px 60px;
}

.menu li:hover {
  background-color: tomato;
  border-radius: 5px;
}

.icons {
  display: flex;
  align-items: center;
}

.icons li {
  font-size: 30px;
  padding-right: 20px;
}

.toggle__btn {
  display: none;
}

@media screen and (max-width: 1200px) {
  .container {
    flex-direction: column;
  }

  .menu {
    display: flex;
    flex-direction: column;
    text-align: center;
    padding-left: 0;
  }

  .icons {
    display: flex;
    justify-content: center;
  }

  .toggle__btn {
    display: flex;
    position: absolute;
    right: 30px;
    font-size: 30px;
  }

  .menu.active,
  .icons.active {
    display: none;  
  }

}

JavaScript

const toggleBtn = document.querySelector('.toggle__btn');
const menu = document.querySelector('.menu');
const icons = document.querySelector('.icons');

toggleBtn.addEventListener('click', () => {
  menu.classList.toggle('active');
  icons.classList.toggle('active');
});

구현하는 방법

  1. JS: addEventListener를 이용해 클릭할때 마다 'active' 클래스가 생겼다가 없어졌다가를 구현하기.
  2. CSS: 구현될 클래스에 .ative일때 display:none;을 설정해주면 완성!

좋은 웹페이지 즐겨찾기