File size: 1,266 Bytes
e66cfb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
(function () {
  function cleanIdFromHash(h) {
    if (!h) return "";
    var s = h.replace(/^#/, "");
    if (s.startsWith("h-")) s = s.slice(2);
    return s;
  }

  function scrollToId(id) {
    if (!id) return;
    var el = document.getElementById(id);
    if (!el) return;
    // ?? CSS ? scroll-margin-top??????? header ??
    el.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
  }

  // 1) ??? #hash ?????????????
  window.addEventListener("load", function () {
    var id = cleanIdFromHash(location.hash);
    if (id) setTimeout(function(){ scrollToId(id); }, 0);
  });

  // 2) hash ????? pushState ??????
  window.addEventListener("hashchange", function () {
    var id = cleanIdFromHash(location.hash);
    if (id) scrollToId(id);
  });

  // 3) ?????? #fragment ???????????
  document.addEventListener("click", function (e) {
    var a = e.target.closest('a[href^="#"]');
    if (!a) return;
    var raw = a.getAttribute("href") || "";
    var id  = cleanIdFromHash(raw);
    if (!id) return;        // ?????????????????
    var el = document.getElementById(id);
    if (!el) return;        // ???????
    e.preventDefault();
    scrollToId(id);
    // ???? hash?????????
    history.pushState(null, "", "#" + id);
  });
})();