Skip to content

Instantly share code, notes, and snippets.

@imilu
Created August 6, 2016 05:48
Show Gist options
  • Save imilu/94a9dfeaeb6227f05cbb128f658b5095 to your computer and use it in GitHub Desktop.
Save imilu/94a9dfeaeb6227f05cbb128f658b5095 to your computer and use it in GitHub Desktop.
适用于Typecho的生成TOC的JS代码
/*
* Copy from shuyz.com
*
* Dynamic Table of Contents script
* by Matt Whitlock <http://www.whitsoftdev.com/>
*/
function createLink(href, innerHTML) {
var a = document.createElement("a");
a.setAttribute("href", href);
a.innerHTML = innerHTML;
return a;
}
function generateTOC(toc) {
var i2 = 0, i3 = 0, i4 = 0;
var indexdiv = document.createElement("h2");
indexdiv.innerHTML = "目录";
indexdiv.className = "index-name";
toc.appendChild(indexdiv);
toc = toc.appendChild(document.createElement("ul"));
var myindex = document.getElementById('main').querySelectorAll("h2, h3, h4")
for (var i = 0; i < myindex.length; ++i) {
var node = myindex[i];
// the title of typecho is "h2" element, we should ignore it
if((node.className == "post-title") || (node.className == "index-name")){
continue;
}
var tagName = node.nodeName.toLowerCase();
if (tagName == "h4") {
++i4;
if (i4 == 1) toc.lastChild.lastChild.lastChild.appendChild(document.createElement("ul"));
var section = i2 + "." + i3 + "." + i4;
node.id = "section" + section;
toc.lastChild.lastChild.lastChild.lastChild.appendChild(document.createElement("li")).appendChild(createLink("#section" + section, node.innerHTML));
}
else if (tagName == "h3") {
++i3, i4 = 0;
if (i3 == 1) toc.lastChild.appendChild(document.createElement("ul"));
var section = i2 + "." + i3;
node.id = "section" + section;
toc.lastChild.lastChild.appendChild(document.createElement("li")).appendChild(createLink("#section" + section, node.innerHTML));
}
else if (tagName == "h2") {
++i2, i3 = 0, i4 = 0;
var section = i2;
node.id = "section" + section;
toc.appendChild(h2item = document.createElement("li")).appendChild(createLink("#section" + section, node.innerHTML));
}
}
// check if the index is empty
indexelements = toc.getElementsByTagName("li");
if(indexelements.length == 0){
document.getElementById("toc").remove();
}
}
try
{
generateTOC(document.getElementById('toc'));
}
// if anything unexpected happened,we'd rather delete the whole toc than output an incomplete one
catch(err)
{
var element = document.getElementById('toc');
if (typeof(element) != 'undefined' && element != null)
{
document.getElementById("toc").remove();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment