const home = document.querySelector('.home__container');
const homeHeight = home.getBoundingClientRect().height;
document.addEventListener('scroll', () => {
home.style.opacity = 1 - window.scrollY / homeHeight;
});
const home = document.querySelector('.home__container');
const homeHeight = home.getBoundingClientRect().height;
home 상수를 정의 = html의 home__container 클래스
homeHeight 상수를 정의 = home의 뷰포트 상의(최종물의) 높이 값
document.addEventListener('scroll', () => {
home.style.opacity = 1 - window.scrollY / homeHeight;
});
addEventListener을 적용한다.('스크롤을 할때' 다음과 같은 공식을 실행한다.{
home에 style속성값을 추가한다.
style : opacity = 1 - 뷰포트 스크롤 값 / home의 뷰포트 높이 값
스크롤 량에 따라 원하는 영역의 투명도를 조절하려면 간단한 수학 연산으로 가능하다.
1에서 (내가 스크롤 한 값 / 영역의 높이 값)으로 투명도 값을 정하면 된다.
투명도는 1(완전한 불투명) ~ 0(완전한 투명)으로 조절할 수 있다.
따라서, 만약 내가 뷰포트에서 100만큼 스크롤을 하고, home의 뷰포트 높이값이 500이라고 할때,
1 - 100/500은 0.2이다.
따라서 오파시티 값은 0.2가 되는것이다.
또,
1- 2000/500은 -3이다.
따라서 오파시티 값은 -3으로 완전한 투명상태(0미만)이 되는것이다.
element.style.style속성은 해당 element에 원하는 style속성을 추가 시켜줄 수 있다.
즉 home.style.opacity = 0.5는
home태그 안에 style속성 중 opacity값을 0.5로 추가할 수 있다.
js에서 css를 추가,수정하는 더 많은 방법은 아래 링크를 참고.