-
[GSAP] scrollTo() ํจ์ ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒCoding 2024. 6. 2. 23:06๋ฐ์ํ
scrollTo()
GSAP์์ ScrollToPlugin์ ์ฌ์ฉํด ๋ธ๋ผ์ฐ์ ์คํฌ๋กค์ ํน์ ์์น๋ก ๋ถ๋๋ฝ๊ฒ ์คํฌ๋กคํ ์ ์์ต๋๋ค.
์ฐ์ ๊ธฐ๋ณธ์ ์ผ๋ก gsap๊ณผ ScrollToPlugin์ ํ๋ก์ ํธ์ ๋ถ๋ฌ์์ผํฉ๋๋ค.
cdn์ ํตํด ๋ถ๋ฌ์ค๊ฒ ์ต๋๋ค.
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.10.4/gsap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.10.4/ScrollToPlugin.min.js"></script>
์ฐฝ์ ์์์ 500px ์์น๋ก ์คํฌ๋กค ์ด๋ํ๋ ค๋ฉด
์ฐ์ 'gsap.to()' ํจ์๋ฅผ ํธ์ถํ๊ณ 'scrollTo' ์์ฑ์ ์ซ์ 500์ ๋ฃ์ด์ ๊ฐ๋จํ๊ฒ ์ด๋์ํฌ ์ ์์ต๋๋ค.
gsap.to(window, {duration: 1, scrollTo: 500});
ํน์ ์์๋ก ์คํฌ๋กคํ ์๋ ์์ต๋๋ค. ์๋ฅผ ๋ค์ด, '#section2'๋ผ๋ ์์๋ก ์คํฌ๋กคํ๋ ค๋ฉด ์๋์ฒ๋ผ ์ ์ด์ฃผ๋ฉด ๋ฉ๋๋ค.
gsap.to(window, {duration: 1, scrollTo: "#section2"});
์ ์์ ๋ค์ 'window' ์ฆ ๊ธฐ๋ณธ ๋ธ๋ผ์ฐ์ ์ฐฝ ์คํฌ๋กค์ ์ปจํธ๋กค ํ๋๊ฒ์ด๋ผ๋ฉด,
์ฐฝ ๋์ ํน์ ์คํฌ๋กค ๊ฐ๋ฅํ ์ปจํ ์ด๋์๋ ํ์ผ์ผ๋ก ์ค์ ํ ์ ์์ต๋๋ค.
gsap.to("#scrollContainer", {duration: 1, scrollTo: {y: 200}});
๊ฐ๋จํ๊ฒ ์คํฌ๋กค ์ ๋๋ฉ์ด์ ์ ์ง์์๊ฐ๊ณผ ์ด์ง ์ต์ ์ ์กฐ์ ํ ์๋ ์์ต๋๋ค.
gsap.to(window, { duration: 1.5, // ์คํฌ๋กค ์๋ ์์ scrollTo: { y: "#section2", // #section2 ์์๋ก ์คํฌ๋กค ์ด๋ offsetY: 50 // ์์ ์ 50ํฝ์ ์์น๋ก ์คํฌ๋กค }, ease: "power2.inOut" // ์ด์ง ์์ });
ํ์ง๋ง ์ ์์ ๋ค์ ํ์ด์ง๊ฐ ๋ก๋ฉ๋๋ฉด ๋ฐ๋ก ์คํฌ๋กค์ด ์ด๋ํด๋ฒ๋ฆฝ๋๋ค.
GSAP์์ ์ ๊ณตํ๋ ํด๋ฆญ ์ ์คํฌ๋กค์ด๋ ์์ ์ ๋๋ค.
document.querySelectorAll("nav button").forEach((btn, index) => { // forEach๋ก ๋ฒํผ๊ณผ ๋ฒํผ index๊ฐ์ ๊ฐ์ ธ์ด btn.addEventListener("click", () => { gsap.to(window, { duration: 1, scrollTo:{ y:"#section" + (index + 1), // (index + 1) = ๊ฐ section ๋ค์ ์ซ์๋ฅผ ๋ปํจ. index๋ 0๋ถํฐ ์์ํ๊ธฐ ๋๋ฌธ์ +1์ ํฉ๋๋ค. offsetY: 70 // section ์ด๋๋ฒํผ์ด ์๋จ fixed๋ก ๊ณ ์ ๋์ด ์๊ธฐ๋๋ฌธ์ ๊ทธ ๊ฐ 70px์ offsetY ๊ฐ์ผ๋ก ์ค์ } }); }); });
GSAP์ ScrollToPlugin์ ์ฌ์ฉํ๋ฉด ์ต์ํ์ ์ฝ๋๋ก ๋ถ๋๋ฌ์ด ์คํฌ๋กค ํจ๊ณผ๋ฅผ ๊ตฌํ ํ ์ ์์ต๋๋ค.
๋ค์๋ฒ์ scrollTo() ํจ์์ ๋ค๋ฅธ ์ต์ ๋ค์ ๋ค๋ค๋ณด๊ฒ ์ต๋๋ค.
์์ธํ ๋ด์ฉ์ GSAP ScrollToPlugin ๋ฌธ์๋ฅผ ์ฐธ๊ณ ํ์ธ์.
๋ฐ์ํ'Coding' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ