스크롤을 조금만 내렸을 때 특정 위치로 스크롤 되는 코드를 구현해야 해서
다음과 같이 만들었다.
window.addEventlistener('scroll', () => {
if (window.scrollY > 100 && window.scrollY < 150) {
window.scrollTo({
top: el.offsetTop,
behavior: 'smooth',
});
}
});
이렇게 했을 때 두가지 문제가 발생했다.
첫째는 스크롤을 내렸다가 올라올때에도 이벤트리스너가 실행된다는 것이었고,
두번째는 사파리에서 behavior 속성을 지원하지 않았다.
따라서 코드를 다음과 같이 바꾸었다.
let scrollBefore;
const Main = () => {
...
useEffect(() => {
smoothscroll.polyfill();
window.addEventlistener('scroll', () => {
const scrollAfter = scrollBefore;
scrollBefore = window.scrollY
if (scrollAfter < scrollBefore) {
console.log('down');
} else {
console.log('up');
}
if (window.scrollY > 100 && window.scrollY < 150 && scrollAfter < scrollBefore) {
scrollBefore = 0;
window.scrollTo({
top: el.offsetTop,
behavior: 'smooth',
});
}
});
}, []);
};
이렇게하여 스크롤이 올라가고 있는 상황인지 내려가고 있는 상황인지 구분할 수 있게 되었다.
사파리에서 scrollTo smooth 가 되지 않던 것은 polyfill 을 install 해서 해결했당
https://www.npmjs.com/package/smoothscroll-polyfill
는 안된다 개빡친다 시123발
'FE > Vanilla' 카테고리의 다른 글
webstorm 전체검색이 되지 않는 현상 (2) | 2021.07.20 |
---|---|
styled-components keyframes (0) | 2021.07.16 |
swiper 에서 뭐 아무튼 width 나 margin이 애매할때 (0) | 2021.04.06 |
swiper slide 가 세로로 정렬될 때 (7) | 2021.04.06 |
css 부모 패딩 무시 (4) | 2021.03.29 |