๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Frontend/JavaScript

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] ๋ถ€๋“œ๋Ÿฝ๊ฒŒ scroll ํ•˜๋Š” ๋ฐฉ๋ฒ• ์•Œ์•„๋ณด๊ธฐ

by YWTechIT 2021. 11. 16.
728x90

๐Ÿ“ ๋ถ€๋“œ๋Ÿฝ๊ฒŒ scroll ํ•˜๋Š” ๋ฐฉ๋ฒ• ์•Œ์•„๋ณด๊ธฐ

medium์„ ๋ณด๋‹ค๊ฐ€ Div์˜ ๋งจ ์•„๋ž˜๋กœ scroll ํ•˜๋Š” ๋ช‡ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•(scrollTop, clientHeight, scrollIntoView)์„ ์ž‘์„ฑํ•œ ๊ธ€์„ ๋ณด๋˜ ์ค‘ scrollIntoView ๋ฉ”์„œ๋“œ๊ฐ€ ๊ฐ„ํŽธํ•ด ๋ณด์—ฌ์„œ ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋กœ ์ง์ ‘ ๊ธฐ๋Šฅ์„ ์ง์ ‘ ๊ตฌํ˜„ํ•˜๋ฉด์„œ ๋ฐฐ์šด ์ ์„ ๋‚จ๊ธด๋‹ค. scrollIntoView ๋ฉ”์„œ๋“œ๋Š” scrollIntoView()๊ฐ€ ํ˜ธ์ถœ ๋œ ์š”์†Œ๊ฐ€ ์‚ฌ์šฉ์ž์—๊ฒŒ ํ‘œ์‹œ๋˜๋„๋ก ์š”์†Œ์˜ ์ƒ์œ„ ์ปจํ…Œ์ด๋„ˆ๋ฅผ ์Šคํฌ๋กคํ•˜๋Š” ๋ฉ”์†Œ๋“œ์ธ๋ฐ, caniuse ์‚ฌ์ดํŠธ์—์„œ ๋ณด๋ฉด ๊ฑฐ์˜ ๋Œ€๋ถ€๋ถ„์˜ ๋ธŒ๋ผ์šฐ์ €์—์„œ ์ง€์›ํ•˜๋ฏ€๋กœ ํฌ๋กœ์Šค ๋ธŒ๋ผ์šฐ์ง•์„ ๊ณ ๋ คํ•  ๋•Œ ์‚ฌ์šฉํ•ด๋„ ๊ดœ์ฐฎ์€ ๋ฉ”์†Œ๋“œ์ธ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

MDN์„ ์ฐธ๊ณ ํ•˜๋ฉด ์•Œ ์ˆ˜ ์žˆ์ง€๋งŒ scrollIntoView ๋ฉ”์„œ๋“œ์˜ ์ธ์ž๋Š” ์ด 2๊ฐœ๋ฅผ ๋ฐ›๋Š”๋ฐ, alignToTop๊ณผ scrollIntoViewOptions๊ฐ€ ๋˜๊ฒ ๋‹ค. ์ฒซ๋ฒˆ์งธ ์ธ์ž์ธ booleanํ˜•ํƒœ์˜ alignToTop=true๋Š” element ์š”์†Œ์˜ ์ƒ๋‹จ์„ ๊ธฐ์ค€์œผ๋กœ, alignToTop=false๋Š” element ์š”์†Œ์˜ ํ•˜๋‹จ์„ ๊ธฐ์ค€์œผ๋กœ ์Šคํฌ๋กค์„ ์„ค์ •ํ•œ๋‹ค.

 

728x90

 

๋‘ ๋ฒˆ์งธ ์ธ์ž์ธ scrollIntoViewOptions๋Š” ์ตœ๋Œ€ 3๊ฐœ์˜ ๊ฐ์ฒด๋กœ ๊ฐ’์„ ๋„˜๊ฒจ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š”๋ฐ, behavior(auto(default) || smooth), block(start(default) || center || end || nearest), inline(start(default) || center || end || nearest) ๊ฐ’์„ ๋„˜๊ฒจ๋ฐ›๋Š”๋‹ค. alignToTop ์ƒ๋žตํ•˜๋”๋ผ๋„ ๋ถ€๋“œ๋Ÿฌ์šด ์›€์ง์ž„์„ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— scrollIntoViewOptions์—์„œ smooth๋ฅผ ํฌํ•จํ–ˆ๊ณ , block์˜ ์ƒ๋‹จ ํ˜น์€ ํ•˜๋‹จ๊นŒ์ง€ ๋‚ด๋ ค๊ฐ€์•ผํ•˜๋ฏ€๋กœ block๋„ ํฌํ•จํ–ˆ๋‹ค. ์ž์„ธํ•œ ์ฝ”๋“œ๋Š” ์ง์ ‘ ์ž‘์„ฑํ•œ copePen์˜ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด ๋œ๋‹ค.  ์‚ด์ง ์ด์ƒํ•œ ์ ์ด codepen browser์—์„œ scrollํ•˜๋ฉด ์ •์ƒ์ ์œผ๋กœ ์ž‘๋™๋˜๋Š”๋ฐ `embed` ํ•œ ๊ฒฐ๊ณผ์—์„œ `scroll` ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด ํ˜„์žฌ document.body๊นŒ์ง€ ๊ฐ™์ด scroll์ด ๋˜๋Š”๋ฐ ์™œ ์ด๋ ‡๊ฒŒ ๋˜๋Š”์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ๋‹ค. ๋ธŒ๋ผ์šฐ์ €๊นŒ์ง€ ์›€์ง์ด๋Š” ๊ฒƒ์ด ๋ถˆํŽธํ•˜๋‹ค๋ฉด ์šฐ์ธก ์ƒ๋‹จ์˜ `edit on codepen` ๊ธ€์„ ๋ˆ„๋ฅด๋ฉด ์‚ฌ์ดํŠธ์— ๋“ค์–ด๊ฐ€์ง€๋Š”๋ฐ ํ•ด๋‹น ์‚ฌ์ดํŠธ์—์„œ ๋ณด๋Š”๊ฒƒ์„ ๊ถŒ์žฅํ•œ๋‹ค. 

 

See the Pen Untitled by an (@YWTechIT) on CodePen.

 

reference

  1. medium
  2. MDN
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€