ํฐ์คํ ๋ฆฌ ๋ทฐ
๋ฌธ์
offsetTop, scrollTop, clientHeight์ ์๊ด๊ด๊ณ๋ฅผ ํตํด ์คํฌ๋กค์ ๋ด๋ฆฌ๋ฉด์ ๋์ค๋ ์ซ์๊ฐ ์๋จ ๋ฉ๋ด์ ํ์ฑํ๋ ์ซ์์ ์ผ์นํ๋๋ก ๊ตฌํ
๋ฌธ์ ํด๊ฒฐ
const navElem = document.querySelector("#nav");
const navItems = Array.from(navElem.children);
const contentsElem = document.querySelector("#contents");
const contentItems = Array.from(contentsElem.children);
const offsetTops = contentItems.map((elem) => {
const [ofs, clh] = [elem.offsetTop, elem.clientHeight];
return [ofs - clh / 2, ofs + clh / 2];
// return [ofs, ofs + clh]
});
window.addEventListener("scroll", (e) => {
const { scrollTop } = e.target.scrollingElement;
const targetIndex = offsetTops.findIndex(([from, to]) => (
scrollTop >= from && scrollTop < to
))
navItems.forEach((item, index) => {
if(index !== targetIndex) {
item.classList.remove('on');
}
else item.classList.add('on');
})
});
Issue
1. ๋ฐ๋ณต๋๋ ์์ ๋ ธ๋๋ฅผ ์ทจ๋ํ ๋, ๋ถ๋ชจ ์์ ๋ ธ๋.children์ ํตํด ๋ชจ๋ ์์ ๋ ธ๋๋ฅผ ๊ฐ์ ธ์ค๊ณ ์ด๋ฅผ Array.from() ๋ฉ์๋๋ฅผ ํตํด
๋ฐฐ์ด ์งํฉ์ ์ ์ฌํ์๋ค.
์ดํ ์ฝ๋ ์์์ map(), forEach() ๋ฐฐ์ด ๋ฉ์๋๋ฅผ ํ์ฉํ์ฌ ๋์ ์ฒ๋ฆฌ๋ฅผ ์ ๋์ ์ผ๋ก ์ฒ๋ฆฌํ ์ ์์๋ค.
2. ํ์ด์ง์ ํ์ด์ง ์ฌ์ด ๊ฐ์ ๋ฒ์ ๋์ ์๋จ ๋ฉ๋ด์ ์ซ์๋ฅผ ํ์ฑํ์์ผ ์ฃผ๊ธฐ ์ํด offsetTop๊ณผ clientHeight์ ์๊ด ๊ด๊ณ๋ฅผ ์ด์ฉ
ํ์ฌ ๊ทธ ๋ฒ์์ ๊ฐ์ ์ถ๋ ค ๋๋ค.
- offsetTop: ์๋์ ์ผ๋ก ๊ฐ์ฅ ๊ฐ๊น์ด ์์น์ ์๋ ์์ ์์์ ๋งจ ์์์๋ถํฐ์ ํฝ์ ์
- clientHeight: ๋ด๋ถ ์ฌ๋ฐฑ(padding)์ ํฌํจ ํ ์๋ฆฌ๋จผํธ์ ๋ด๋ถ ๋์ด๋ฅผ ํฝ์ ๋ก ๋ฐํ
3. ํ์ฌ ์คํฌ๋กค ๋ฐ์ ์์น๋ฅผ ๊ฐ์ ธ์ค๊ธฐ ์ํด element.scrollingElement์ ํ๋กํผํฐ scrollTop์ ๋์คํธ๋ญ์ณ๋ง
4. ํ์ฌ ์คํฌ๋กค ๋ฐ์ ์์น์ ํด๋น ๋์ ํจ๊ณผ๊ฐ ์ ์ฉ ๋ ๋ฒ์๋ฅผ ๋น๊ต ๋ฐ ์ธ๋ฑ์ค๋ฅผ ์๋ณํด์ฃผ๊ธฐ ์ํด Array.findIndex() ๋ฉ์๋๋ฅผ ์ฌ์ฉ
ํ์ฌ ์์๊ณผ ๋์ ๋ฒ์ ๊ฐ ๋ด์ ์คํฌ๋กค ๋ฐ์ ํ์ฌ ์์น๊ฐ ์กด์ฌํ๋ค๋ฉด ํด๋น ํ์ด์ง์ ์ธ๋ฑ์ค๋ฅผ ๋ฐํ
'JS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Debounce ํจ์๋ก ์ด๋ฒคํธ ์ฒ๋ฆฌ ์ต์ ํ (0) | 2021.07.01 |
---|---|
Infinite Scroll (0) | 2021.07.01 |
Context Menu (0) | 2021.06.01 |
๋ด์ฅ ํจ์ call์ this ๋ฐ์ธ๋ฉ (0) | 2021.04.17 |
dataset data-id์ ์ด์ฉํด ์ด๋ฒคํธ ์์ (0) | 2021.04.14 |