๐ŸŸจ JavaScript/์‘์šฉํ•˜์—ฌ ์ž๋™ํ™”or๋ฌธ์ œํ•ด๊ฒฐํ•˜๊ธฐ

๋ฌธ์ œํ•ด๊ฒฐ : hash๊ฐ’ ๋ฐ›์•„์„œ scroll ์กฐ์ •ํ•˜๊ธฐ

Zoeeey 2023. 5. 12. 14:25

์ƒํ™ฉ

 A ํŽ˜์ด์ง€์—์„œ aํƒœ๊ทธ ์—ฌ๋Ÿฌ๊ฐœ์— ๋งํฌ๋ฅผ ๊ฑธ์–ด์„œ ๋ˆ„๋ฅด๋ฉด BํŽ˜์ด์ง€์˜ ๊ฐ๊ฐ ๋‹ค๋ฅธ ์œ„์น˜๋กœ ์—ฐ๊ฒฐ๋˜๊ฒŒ ํ•˜๋ ค๊ณ  ํ•œ๋‹ค. (์—ฌ๊ธฐ์„œ AํŽ˜์ด์ง€์™€ BํŽ˜์ด์ง€๋Š” ๊ฐ๊ธฐ ๋‹ค๋ฅธ HTML์ด๋‹ค.)

AํŽ˜์ด์ง€

<div class="link">
    <a href="../folder/text.html#content01">์ œ๋ชฉ1</a>
    <a href="../folder/text.html#content02">์ œ๋ชฉ2</a>
    <a href="../folder/text.html#content03">์ œ๋ชฉ3</a>
    <a href="../folder/text.html#content04">์ œ๋ชฉ4</a>
	...
</div>

BํŽ˜์ด์ง€

<h4 id="content01">์ปจํ…์ธ  ์ œ๋ชฉ 1</h4>
<div>์ปจํ…์ธ  ...</div>
<h4 id="content02">์ปจํ…์ธ  ์ œ๋ชฉ 2</h4>
<div>์ปจํ…์ธ  ...</div>
<h4 id="content03">์ปจํ…์ธ  ์ œ๋ชฉ 3</h4>
<div>์ปจํ…์ธ  ...</div>
<h4 id="content04">์ปจํ…์ธ  ์ œ๋ชฉ 4</h4>
<div>์ปจํ…์ธ  ...</div>
<h4 id="content05">์ปจํ…์ธ  ์ œ๋ชฉ 5</h4>
<div>์ปจํ…์ธ  ...</div>
...

๋ฌธ์ œ

ํ•ญ์ƒ ์ƒ๋‹จ์— css๊ฐ€ fixed๋กœ ๊ณ ์ •๋˜๋Š” header๊ฐ€ ์žˆ์–ด์„œ ๋งํฌ๋กœ ์ด๋™ํ–ˆ์„ ์‹œ ์›ํ•˜๋Š” ์ •ํ™•ํ•œ ์œ„์น˜์˜ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋ณด์ด์ง€ ์•Š๊ณ  ์ค‘๊ฐ„๋ถ€ํ„ฐ ๋ณด์ด๋Š” ํ˜„์ƒ์ด ์žˆ์—ˆ๋‹ค.


์กฐ๊ฑด

AํŽ˜์ด์ง€์—์„œ aํƒœ๊ทธ๋ฅผ ๋ˆ„๋ฅด๋ฉด BํŽ˜์ด์ง€์˜ ํ•ด๋‹น ํ•ด์‹œ์•„์ด๋””๋ฅผ ๊ฐ€์ง„ h4๊ฐ€ header ๋ฐ”๋กœ ์•„๋ž˜ ์˜ค๋„๋ก ์Šคํฌ๋กค์ด ์ด๋™๋˜์–ด์•ผ ํ•œ๋‹ค.


ํ•ด๊ฒฐ

BํŽ˜์ด์ง€์—์„œ ์•„๋ž˜ ์ฝ”๋“œ๋ฅผ ์‹คํ–‰์‹œ์ผœ์ฃผ์—ˆ๋‹ค.

// URL์˜ ํ•ด์‹œ๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ๋งˆ๋‹ค ์Šคํฌ๋กค ์œ„์น˜ ์กฐ์ •
window.addEventListener("hashchange", function() {
  var hash = location.hash;
  if (hash !== "") {
    var target = document.querySelector(hash);
    if (target) {
      var headerHeight = document.querySelector("header").offsetHeight;
      var targetPosition = target.getBoundingClientRect().top;
      window.scrollTo({
        top: targetPosition + window.pageYOffset - headerHeight - 100,
        behavior: "smooth"
      });
    }
  }
});

// ์ดˆ๊ธฐ ๋กœ๋”ฉ ์‹œ URL์˜ ํ•ด์‹œ๊ฐ’์— ๋”ฐ๋ผ ์Šคํฌ๋กค ์œ„์น˜ ์กฐ์ •
window.addEventListener("load", function() {
  var hash = location.hash;
  if (hash !== "") {
    var target = document.querySelector(hash);
    if (target) {
      var headerHeight = document.querySelector("header").offsetHeight;
      var targetPosition = target.getBoundingClientRect().top;
      window.scrollTo({
        top: targetPosition + window.pageYOffset - headerHeight - 100,
        behavior: "auto"
      });
    }
  }
});

ํ•ด๋‹น ์ฝ”๋“œ๋Š” ํŽ˜์ด์ง€ ๋กœ๋”ฉ ์‹œ ๋ธŒ๋ผ์šฐ์ €์˜ URL์—์„œ ํ•ด์‹œ๊ฐ’์„ ์ถ”์ถœํ•˜๊ณ , ํ•ด๋‹น ํ•ด์‹œ๊ฐ’์„ ๊ฐ€์ง„ ์š”์†Œ๊ฐ€ ์žˆ๋Š”์ง€ ์ฐพ๋Š”๋‹ค. ๊ทธ๋ฆฌ๊ณ  ํ•ด๋‹น ์š”์†Œ์˜ ์œ„์น˜๋ฅผ ๊ณ„์‚ฐํ•˜์—ฌ ์Šคํฌ๋กค ์œ„์น˜๋ฅผ ์กฐ์ •ํ•œ๋‹ค.
๋˜ํ•œ, URL์˜ ํ•ด์‹œ๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ๋งˆ๋‹ค ์Šคํฌ๋กค ์œ„์น˜๋ฅผ ์กฐ์ •ํ•˜๋„๋ก ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ๋ฅผ ๋“ฑ๋กํ–ˆ๋‹ค.