script.html 608 B

12345678910111213141516171819202122232425262728293031323334
  1. <script>
  2. headings = [];
  3. onload = function(){
  4. headings = document.querySelectorAll('h2');
  5. };
  6. onscroll = function(e){
  7. var heading = find(window.scrollY);
  8. if (!heading) return;
  9. var links = document.querySelectorAll('#menu a')
  10. , link;
  11. for (var i = 0, len = links.length; i < len; ++i) {
  12. link = links[i];
  13. link.className = link.getAttribute('href') == '#' + heading.id
  14. ? 'active'
  15. : '';
  16. }
  17. };
  18. function find(y) {
  19. var i = headings.length
  20. , heading;
  21. while (i--) {
  22. heading = headings[i];
  23. if (y >= heading.offsetTop) {
  24. return heading;
  25. }
  26. }
  27. }
  28. </script>