生成目录一
只需要把下面代码加到html head上就行
document.addEventListener(“DOMContentLoaded”, function() {
// 生成目录列表
var outline = document.createElement(“ul”);
outline.setAttribute(“id”, “outline-list”);
outline.style.cssText = “border: 1px solid #ccc;”;
document.body.insertBefore(outline, document.body.childNodes[0]);
// 获取所有标题
var headers = document.querySelectorAll(‘h1,h2,h3,h4,h5,h6’);
for (var i = 0; i < headers.length; i++) {
var header = headers[i];
var hash = _hashCode(header.textContent);
// MarkdownPad2无法为中文header正确生成id,这里生成一个
header.setAttribute(“id”, header.tagName + hash);
// 找出它是H几,为后面前置空格准备
var prefix = parseInt(header.tagName.replace(‘H’, ”), 10);
outline.appendChild(document.createElement(“li”));
var a = document.createElement(“a”);
// 为目录项设置链接
a.setAttribute(“href”, “#” + header.tagName + hash)
// 目录项文本前面放置对应的空格
a.innerHTML = new Array(prefix * 4).join(‘ ’) + header.textContent;
outline.lastChild.appendChild(a);
}
});
// 类似Java的hash生成方式,为一段文字生成一段基本不会重复的数字
function _hashCode(txt) {
var hash = 0;
if (txt.length == 0) return hash;
for (i = 0; i < txt.length; i++) {
char = txt.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
生成目录二
document.addEventListener("DOMContentLoaded", function() {
// 生成目录列表
var div1 = document.createElement("div");
div1.style.cssText = "clear:both";
var outline = document.createElement("div");
outline.setAttribute("id", "outline-list");
outline.style.cssText = "border:solid 1px #ccc; background:#eee; min-width:200px;padding:4px 10px;";
var ele_p = document.createElement("p");
ele_p.style.cssText = "text-align: left; margin: 0;";
outline.appendChild(ele_p);
var ele_span = document.createElement("span");
// ele_span.style.cssText = "float: left;";
var ele_text=document.createTextNode("目录");
ele_span.appendChild(ele_text);
var ele_a = document.createElement("a");
ele_a.appendChild(document.createTextNode("[+]"));
ele_a.setAttribute("href", "#");
ele_a.setAttribute("onclick", "javascript:return openct(this);");
ele_a.setAttribute("title", "点击打开目录");
ele_span.appendChild(ele_a);
ele_p.appendChild(ele_span);
var ele_ol = document.createElement("ol");
ele_ol.style.cssText = "display:none;margin-left:14px;padding-left:14px;line-height:160%;";
ele_ol.setAttribute("id", "outline_ol");
outline.appendChild(ele_ol);
var div1 = document.createElement("div");
div1.style.cssText = "clear:both";
document.body.insertBefore(outline, document.body.childNodes[0]);
// 获取所有标题
var headers = document.querySelectorAll('h1,h2,h3,h4,h5,h6');
if (headers.length