2
0

table-of-contents.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. var table = document.querySelector(".c-r div"),
  2. list = table.querySelector(".c-r ol"),
  3. examples = document.getElementsByClassName("example"),
  4. header_height = document.querySelector(".hero").clientHeight,
  5. table_of_contents, table_of_scrolls = [];
  6. function onScroll (e){
  7. if (window.pageYOffset > header_height - (e ? e.deltaY||16 : 16))
  8. table.classList.add("fixed");
  9. else
  10. table.classList.remove("fixed");
  11. highlightActive(e);
  12. }
  13. function highlightActive(e) {
  14. var currentActive = document.getElementsByClassName("current")[0];
  15. if (currentActive) {
  16. currentActive.className = ""
  17. }
  18. for (var i = table_of_scrolls.length - 1; i >=0; --i) {
  19. if (window.pageYOffset + (e ? e.deltaY : 0) >= table_of_scrolls[i]) {
  20. table_of_contents[i].classList.add("current");
  21. break;
  22. }
  23. }
  24. }
  25. function init() {
  26. for (var i = 0; i < examples.length; ++i) {
  27. var item = document.createElement("li"),
  28. link = document.createElement("a");
  29. item.innerHTML = "<span>"+ (i+1 + ". ") + "</span>";
  30. link.href="#"+examples[i].id;
  31. link.innerText=examples[i].getElementsByTagName("h3")[0].innerText||examples[i].getElementsByTagName("h2")[0].innerText;
  32. item.appendChild(link);
  33. list.appendChild(item);
  34. table_of_scrolls.push(window.pageYOffset + examples[i].getBoundingClientRect().top);
  35. }
  36. table_of_contents = list.querySelectorAll("li");
  37. onScroll();
  38. window.addEventListener("wheel", onScroll, {passive: true});
  39. list.addEventListener("click", function(e){
  40. var currentActive = document.getElementsByClassName("current")[0];
  41. if (currentActive) {
  42. currentActive.className = "";
  43. }
  44. e.target.parentNode.className = "current";
  45. });
  46. }
  47. function debounce(func, wait, immediate) {
  48. var timeout;
  49. return function() {
  50. var context = this, args = arguments;
  51. var later = function() {
  52. timeout = null;
  53. if (!immediate) func.apply(context, args);
  54. };
  55. var callNow = immediate && !timeout;
  56. clearTimeout(timeout);
  57. timeout = setTimeout(later, wait);
  58. if (callNow) func.apply(context, args);
  59. };
  60. };
  61. if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))
  62. init();