mine.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var $window = $(window);
  2. var hash = window.location.hash;
  3. window.location.hash = ''; // avoid going to anchor
  4. $window.on('load', function() {
  5. var content = $('#content');
  6. var size = 24; // magic number !
  7. content.find('h2:last').add('h2:last ~ *').each(function() {
  8. size += $(this).outerHeight(true);
  9. });
  10. content.css('margin-bottom', $window.height() - size);
  11. $('#toc').sticky({topSpacing:30});
  12. var navs = $('#side-nav ul li a');
  13. var navItemsMap = {};
  14. var navItems = navs.map(function(_, item) {
  15. var anchor = item.getAttribute('href');
  16. var anchorItem = $(anchor);
  17. var navItem = {
  18. 'nav': $(item),
  19. 'anchor': {'name': anchor, 'item': anchorItem},
  20. 'pos': anchorItem.offset().top
  21. };
  22. navItemsMap[anchor] = navItem;
  23. return navItem;
  24. });
  25. $window.scroll(function(){
  26. var nav;
  27. var pos = $window.scrollTop();
  28. $.each(navItems, function(_, item) {
  29. return pos > item.pos - 1 ? nav = item.nav : false;
  30. });
  31. if (nav) {
  32. navs.removeClass('active');
  33. nav.addClass('active');
  34. }
  35. });
  36. if (hash) {
  37. goTo(hash);
  38. } else {
  39. navs.first().addClass('active');
  40. }
  41. navs.on('click',function(e){
  42. e.preventDefault();
  43. goTo(e.currentTarget.getAttribute('href'));
  44. });
  45. function goTo(hash) {
  46. $('body,html').animate(
  47. {scrollTop: navItemsMap[hash].pos}, 1000, 'swing',
  48. function() {
  49. window.location.hash = hash;
  50. }
  51. );
  52. }
  53. });