-
Notifications
You must be signed in to change notification settings - Fork 103
/
nav.js
131 lines (105 loc) · 3.04 KB
/
nav.js
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// Adapted from Javascript Garden, a MIT project.
function Sections(page) {
this.page = page;
this.init();
}
Sections.prototype = {
init: function(attribute) {
this.heights = this.page.nav.find('ul').map(function(idx, ele) {
return $(this).outerHeight();
}).get();
},
map: function() {
this.names = $('h2').map(function(idx, ele) {
return {
id: this.id,
offset: $(this).offset().top - 20,
title: $(this).find(':header:first').html()
};
}).get();
},
highlight: function() {
var scroll = this.page.window.scrollTop(),
articleID = this.names[this.names.length - 1].id;
$('a').removeClass('active');
var $el;
for(var i = 0, l = this.names.length; i < l; i++) {
if (this.names[i].offset > scroll) {
$el = $("[href='#" + this.names[i].id + "']");
var s = $el.parents('ul')[0];
$el.addClass('active');
if (s !== window.section) {
$(window.section).slideUp();
$(s).slideDown();
window.section = s;
}
break;
}
}
},
updateLinks: function(index) {
if (index !== this.names.length - 1) {
this.setLink(this.links.next, this.names[index + 1]);
} else {
this.links.next.slideUp(100);
}
if (index !== 0) {
this.setLink(this.links.prev, this.names[index - 1]);
} else {
this.links.prev.slideUp(100);
}
},
setLink: function(ele, data) {
ele.slideDown(100).attr('href', '#' + data.id)
.find('.nav_section_name').html(data.title);
}
};
function Page() {
$.extend(true, this, {
window: $(window),
nav: $('.nav > ul > li'),
section: null,
articule: null
});
this.sections = new Sections(this);
this.init();
}
Page.prototype = {
init: function() {
var that = this,
mainNav = $('.toc');
$.extend(this, {
scrollLast: 0,
resizeTimeout: null
});
this.window.scroll(function() {
that.onScroll();
});
this.window.resize(function() {
that.onResize();
});
that.sections.map();
setTimeout(function() {
that.sections.highlight();
}, 10);
},
onScroll: function() {
if ((+new Date()) - this.scrollLast > 50) {
this.scrollLast = +new Date();
this.sections.highlight();
}
},
onResize: function() {
clearTimeout(this.resizeTimeout);
}
};
$(document).ready(function() {
var page = new Page();
page.scrolllast = new Date();
var toc = $(".toc").html();
$("#sidebar").html(toc);
$(".toc").empty();
$('#sidebar ul ul').hide();
$('#sidebar ul ul').first().show();
hljs.initHighlightingOnLoad();
});