하고싶었던 것
- 마우스가 뷰포트 상단으로 위치하면 header가 나타난다.
- 스크롤이 main section에 있으면 header가 사라지지 않는다.
- 스크롤이 main section을 벗어나면 fixed된 header가 사라진다.
마주한 문제
- 마우스의 y좌표만 계산해서 해당 좌표가 100 이하이면 header가 나오도록 했다.
- 마우스 이벤트가 1번만 실행이 되어서 커서가 뷰포트를 벗어나야지만 이벤트가 실행됐다. 페이지를 이용하다가 언제든지 뷰포트 상단에 마우스를 오버하면 header가 보이게 하고 싶었기 때문에 적절하지 않았다.
- 페이지 전체에 mousemove 이벤트를 걸어서 마우스의 좌표가 100 이하이면 header가 보이게 했다.
- main section의 height는 800px이기때문에 스크롤이 main section에 위치하고 있어도 마우스가 상단에 있지 않으면 header가 사라졌다.
document.addEventListener("mouseover", (e) => {
const mouseY = e.clientY;
if (mouseY < 100) {
gsap.to(header, .4, {
opacity: 1,
top: 0
});
} else {
gsap.to(header, .4, {
opacity: 0,
top: '-100px'
});
};
});
해결방법
- document.addEventListener("mousemove')로 문서 전체에 이벤트를 건다.
- if문의 이용하여 '마우스의 y좌표 < 100 || window.scrollY < 500' 두 개의 조건을 걸었다.
코드
if ( document.addEventListener ) {
document.addEventListener("mousemove", headerShow, false);
} else if ( document.attachEvent ) {
document.attachEvent("onmousemove", headerShow);
} else {
document.onmousemove = headerShow;
}
function headerShow (e) {
const axisY = e.clientY;
if (axisY < 100 || window.scrollY < 500) {
gsap.to(header, .4, {
opacity: 1,
top: 0
})
} else {
gsap.to(header, .4, {
opacity: 0,
top: '-100px'
});
}
}