개발일지

스크롤 위치에 따라 네비바 요소 변경하기

이경욱 2023. 10. 25. 21:13

투명도는 숫자로 계산되기 때문에

스크롤 위치와 타겟 위치를 출력하여 opacity값과 계산을 해준다면

자바스크립트에서 간단하게 투명도 조절이 가능해진다

nav.style.opacity = 1 - scrollposition / headerHeight

 

DOM API에 접근해서 요소를 가져온 후

요소의 높이값을 구해준 데이터를 변수에 넣어준다.

조건문으로 현재 스크롤 값과 변수의 높이값을 비교해서

조건이 성립되었을 때 스타일 배경색을 변경하는 코드를 추가했다.

// 헤더 스크롤 애니메이션
document.addEventListener('scroll', onScroll, {passive:true});

function onScroll () {
  const header = document.querySelector('header');
  const title = document.querySelector('.title')

  const titleHeight = title.clientHeight;
  const scrollposition = pageYOffset;
  const nav = document.querySelector('.navbar');

  if (titleHeight <= scrollposition) {
    nav.style.backgroundColor = '#4747478e' // 색상 변경  #4747478e
  } else {
    nav.style.backgroundColor = '#00000000'
  };
}