-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.js
366 lines (323 loc) · 9.06 KB
/
index.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(function () {
return factory;
});
} else if (typeof exports === 'object') {
module.exports = factory;
} else {
root.katelog = factory;
}
})(window, function (opts) {
let defaultOpts = {
linkClass: 'k-catelog-link',
linkActiveClass: 'k-catelog-link-active',
supplyTop: 0,
selector: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
active: null // 激活时候回调
};
if (typeof Object.assign != 'function') {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assign", {
value: function assign(target, varArgs) { // .length of function is 2
'use strict';
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}
/**
* 判断是否有class
* @param node 节点
* @param className 样式名
* @returns {*}
*/
function hasClass(node, className) {
if (node.className) {
return node.className.match(
new RegExp('(\\s|^)' + className + '(\\s|$)'));
} else {
return false;
}
};
/**
* 添加样式
* @param node 节点
* @param className 样式名
*/
function addClass(node, className) {
if (!hasClass(node, className)) node.className += " " + className;
};
/**
* 移除样式
* @param node 节点
* @param className 将移除的样式
*/
function removeClass(node, className) {
if (hasClass(node, className)) {
var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
node.className = node.className.replace(reg, ' ');
}
};
function arrayLikeToArray(al) {
return Array.prototype.slice.call(al);
}
/**
* 获取目录树
* @param catelogs
*/
function getCatelogsTree(catelogs) {
let title, tagName,
tree = [], treeItem = {}, parentItem = { id: -1 }, lastTreeItem = null;
let id;
for (let i = 0; i < catelogs.length; i++) {
title = catelogs[i].innerText || catelogs[i].textContent;
tagName = catelogs[i].tagName;
id = 'heading-' + i;
catelogs[i].id = id;
treeItem = {
name: title,
tagName: tagName,
id: id,
level: getLevel(tagName),
parent: parentItem
};
if (lastTreeItem) {
if (getPriority(treeItem.tagName) < getPriority(lastTreeItem.tagName)) {
treeItem.parent = lastTreeItem;
} else {
treeItem.parent = findParent(treeItem, lastTreeItem);
}
}
lastTreeItem = treeItem;
tree.push(treeItem);
}
return tree;
}
/**
* 找到当前节点的父级
* @param currTreeItem
* @param lastTreeItem
* @returns {*|Window}
*/
function findParent(currTreeItem, lastTreeItem) {
let lastTreeParent = lastTreeItem.parent;
while (lastTreeParent && (getPriority(currTreeItem.tagName) >= getPriority(lastTreeParent.tagName))) {
lastTreeParent = lastTreeParent.parent;
}
return lastTreeParent || { id: -1 };
}
/**
* 获取等级
* @param tagName
* @returns {*}
*/
function getLevel(tagName) {
return tagName ? tagName.slice(1) : 0;
}
/**
* 获取权重
*/
function getPriority(tagName) {
let priority = 0;
if (tagName) {
switch (tagName.toLowerCase()) {
case 'h1':
priority = 6;
break;
case 'h2':
priority = 5;
break;
case 'h3':
priority = 4;
break;
case 'h4':
priority = 3;
break;
case 'h5':
priority = 2;
break;
case 'h6':
priority = 1;
break;
}
}
return priority;
}
/**
* 绑定事件
* @param obj
* @param type
* @param fn
*/
function addEvent(obj, type, fn) {
if (obj) {
if (obj.attachEvent) {
obj['e' + type + fn] = fn;
obj[type + fn] = function () {
obj['e' + type + fn](window.event);
};
obj.attachEvent('on' + type, obj[type + fn]);
} else {
obj.addEventListener(type, fn, false);
}
}
};
/**
* 生成树
* @param tree
*/
function generateHtmlTree(tree, _parent) {
let ul, hasChild = false;
if (tree) {
ul = '<ul>';
for (let i = 0; i < tree.length; i++) {
if (isEqual(tree[i].parent, _parent)) {
hasChild = true;
ul += `<li><div class="${option.linkClass} k-catelog-level-${tree[i].level}" data-target="${tree[i].id}">` + tree[i].name + '</div>';
ul += generateHtmlTree(tree, tree[i]);
ul += '</li>';
}
}
ul += '</ul>'
}
return hasChild ? ul : '';
}
/**
* 获取dataset属性
* @param el
* @param id
* @returns {*}
*/
function getDataset(el, id) {
if (el.dataset) {
return el.dataset[id];
} else {
return el.getAttribute(`data-${id}`)
}
}
function isEqual(node, node2) {
return node && node2 && typeof node === 'object' && typeof node2 === 'object' && node.id === node2.id
}
/**
* 获取滚动条滚动的高度
* @returns {number}
*/
function getScrollTop() {
return document.documentElement.scrollTop || document.body.scrollTop;
}
const option = Object.assign({}, defaultOpts, opts);
const $content = this.contentEl =
option.contentEl instanceof HTMLElement ? option.contentEl : document.getElementById(option.contentEl); // 内容元素
const $catelog =
option.catelogEl instanceof HTMLElement ? option.catelogEl : document.getElementById(option.catelogEl); // 目录元素
let allCatelogs = $content.querySelectorAll(option.selector.join());
let tree = getCatelogsTree(allCatelogs);
let clickToScroll = false; // 点击跳转不触发scroll事件
$catelog.innerHTML = generateHtmlTree(tree, { id: -1 });
let styleText = `
.k-catelog-list > ul { position: relative; }
`
let styleNode = document.createElement('style');
styleNode.type = 'text/css';
if (styleNode.styleSheet) {
styleNode.styleSheet.cssText = styleText;
} else {
styleNode.innerHTML = styleText;
}
document.getElementsByTagName('head')[0].appendChild(styleNode);
addEvent($catelog, 'click', function (e) {
const target = e.target || e.srcElement;
const id = target.getAttribute('data-target');
if (id) {
let headEl = document.getElementById(id);
clickToScroll = true;
const scrollTop = getElementTop(headEl)
window.scrollTo(0, scrollTop - option.supplyTop);
setActiveItem(id);
}
});
/**
* 设置选中的项
*/
function setActiveItem(id) {
let catelogs = $catelog.querySelectorAll('[data-target]');
catelogs = arrayLikeToArray(catelogs);
let activeTarget = null, c;
for (let i = 0; i < catelogs.length; i++) {
c = catelogs[i];
if (getDataset(c, 'target') === id) {
addClass(c, option.linkActiveClass)
activeTarget = c;
const top = getElementTop(c, $catelog)
$catelog.scrollTop = top - $catelog.offsetHeight / 2
// c.scrollIntoView({
// behavior: 'smooth'
// })
} else {
removeClass(c, option.linkActiveClass)
}
}
if (typeof option.active === 'function') {
option.active.call(this, activeTarget);
}
}
/**
* 滚动处理事件
* @param e
*/
function resolveScroll(e) {
// 鼠标滚动则触发,点击滚动不触发
if (!clickToScroll) {
let scrollTop = getScrollTop() + option.supplyTop;
let scrollToEl = null;
for (let i = allCatelogs.length - 1; i >= 0; i--) {
if (getElementTop(allCatelogs[i]) <= scrollTop) {
scrollToEl = allCatelogs[i];
break;
}
}
if (scrollToEl) setActiveItem(scrollToEl.id);
else setActiveItem(null); // 无匹配的元素
}
clickToScroll = false;
}
/**
* 获取元素距离顶部的距离
* @param {*} el
*/
function getElementTop(el, by = null) {
let top = el.offsetTop;
while (el = el.offsetParent) {
if (by === el) {
break
}
top += el.offsetTop;
}
return top;
}
addEvent(window, 'scroll', resolveScroll);
// fix https://github.com/KELEN/k-catelog/issues/1
// 重新构建目录
this.rebuild = function () {
allCatelogs = $content.querySelectorAll(option.selector.join());
let tree = getCatelogsTree(allCatelogs);
$catelog.innerHTML = generateHtmlTree(tree, { id: -1 });
}
});