mine.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. $(document).ready(function() {
  2. $('#toc').sticky({
  3. topSpacing:30,
  4. widthFromWrapper: false
  5. });
  6. $('#side-nav ul li:first-child a').addClass('active')
  7. $('#side-nav ul li a').on('click',function(e){
  8. e.preventDefault();
  9. var target = ($(this).attr('href')).substr(1);
  10. $('body,html').animate({
  11. scrollTop: $('#'+target).offset().top
  12. }, 1000,'swing', function(){
  13. window.location.hash = '#'+target;
  14. });
  15. $('#side-nav ul li a').removeClass('active');
  16. $(this).addClass('active');
  17. });
  18. var lastId,
  19. sideMenu = $('#toc ul'),
  20. // All list items
  21. menuItems = sideMenu.find('a'),
  22. // Anchors corresponding to menu items
  23. scrollItems = menuItems.map(function(){
  24. var item = $($(this).attr('href'));
  25. if (item.length) { return item; }
  26. });
  27. // Bind to scroll
  28. $(window).scroll(function(){
  29. // Get container scroll position
  30. var fromTop = $(this).scrollTop() + 80;
  31. if (fromTop > $('#side-content h2').offset().top) {
  32. // Get id of current scroll item
  33. var cur = scrollItems.map(function(){
  34. if ($(this).offset().top < fromTop)
  35. return this;
  36. });
  37. // Get the id of the current element
  38. cur = cur[cur.length-1];
  39. var id = cur && cur.length ? cur[0].id : '';
  40. if (lastId !== id) {
  41. lastId = id;
  42. // Set/remove active class
  43. //window.location.hash = '#'+id;
  44. menuItems
  45. .removeClass('active')
  46. .filter('[href=#'+id+']').addClass('active');
  47. }
  48. }
  49. });
  50. });