본문 바로가기

Web design

[Navbar] Change Menu Color - Html, CSS, JS

728x90
반응형

Change Menu Color

 

See the Pen abBbvxm by Eunji Jeon (@emcjrl) on CodePen.

 

Html


<body>
  <nav class="menu">
    <a href="#" class="menu_link">Home</a>
    <a href="#" class="menu_link">About</a>
    <a href="#" class="menu_link">Books</a>
    <a href="#" class="menu_link">Portfolio</a>
    <a href="#" class="menu_link">Contact</a>
  </nav>
</body>

 

 

CSS


body {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  font-family:Georgia, 'Times New Roman', Times, serif;
}

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

.menu_link {
  font-size: 1.2em;
  color: rgb(183, 202, 209);
  padding: 0 20px;
  list-style: none;
  text-decoration: none;
}

.menu_active {
  color:darkcyan;
}

 

 

JavaScript 1


let currentMenu; // 현재 활성화된 메뉴를 담을 변수
let menu = document.querySelector('.menu');

function clickHandler(e) {
  if(currentMenu) {
    currentMenu.classList.remove('menu_active');
  }

  e.target.classList.add('menu_active');
  currentMenu = e.target;
};

menu.addEventListener('click', clickHandler);

 

JavaScript 2


let currentMenu; // 현재 활성화된 메뉴를 담을 변수
let menu = document.querySelector('.menu');

const activate = function(elem) {
  elem.classList.add('menu_active');
  currentMenu = elem;
}

const inactivate = function(elem) {
  elem.classList.remove('menu_active');
}

function clickHandler(event) {
  if(currentMenu) {
    inactivate(currentMenu);
  }
  activate(event.target);
}

menu.addEventListener('click', clickHandler);
728x90
반응형