[JS] 스크롤 내리면 메뉴바 색깔 변하게 만들기

MOONJUNG·2022년 7월 22일
0

JavaScript

목록 보기
1/5
post-thumbnail

브라우저에서 스크롤을 내리면 메뉴바 색깔이 변하도록 구현해보기

변경 전

변경 후

HTML

<section id="menu">
      <div class="menu__logo">logo</div>
      <ul class="menu__categories">
        <li class="menu__items">Home</li>
        <li class="menu__items">About me</li>
        <li class="menu__items">Skills</li>
        <li class="menu__items">My work</li>
        <li class="menu__items">Contact</li>
      </ul>
    </section>

CSS

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
li {
  list-style: none;
}
body {
  background-color: #333;
  min-width: 600px;
  height: 3000px;
}
#menu {
  display: flex;
  justify-content: space-between;
  background-color: yellow;
  transition: all 300ms ease;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
#menu.active {
  background: transparent;
  color: yellow;
}
.menu__logo {
  width: 100px;
  height: 60px;
  background-color: tomato;
  color: white;
  text-align: center;
  line-height: 60px;
}
.menu__categories {
  display: flex;
  align-items: center;
}
.menu__items {
  margin-right: 30px;
}

JS

const menu = document.querySelector('#menu');
const menuHeight = menu.getBoundingClientRect().height;

document.addEventListener('scroll', () => {
  if (window.scrollY > menuHeight) {
    menu.classList.add('active');
  } else {
    menu.classList.remove('active');
  }
});
  1. html 태그에서 메뉴에 해당하는 영역을 menu 변수에 담는다
  2. getBoundingClientRect 함수를 통해 메뉴의 height값을 불러온다
  3. 스크롤 height > 메뉴 height → active라는 클래스를 추가
    스크롤 height < 메뉴 height → active라는 클래스를 제거
profile
뜨거운 열정으로 꿈을 실현하는 프론트엔드 개발자 장문정

0개의 댓글