-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmd-toc.min.js
16 lines (16 loc) · 2.65 KB
/
md-toc.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(function(b){function a(d,c){this.el=document.getElementById(d);if(!this.el){return;}this.options=c||{};this.tocLevel=parseInt(c.level)||0;this.tocClass=c["class"]||"toc";
this.tocTop=parseInt(c.top)||0;this.elChilds=this.el.children;if(!this.elChilds.length){return;}this._init();}a.prototype._init=function(){this._collectTitleElements();
this._createTocContent();this._showToc();};a.prototype._collectTitleElements=function(){this._elTitlesNames=[],this.elTitleElements=[];for(var d=1;d<7;
d++){if(this.el.getElementsByTagName("h"+d).length){this._elTitlesNames.push("h"+d);}}this._elTitlesNames.length=this._elTitlesNames.length>this.tocLevel?this.tocLevel:this._elTitlesNames.length;
for(var c=0;c<this.elChilds.length;c++){this._elChildName=this.elChilds[c].tagName.toLowerCase();if(this._elTitlesNames.toString().match(this._elChildName)){this.elTitleElements.push(this.elChilds[c]);
}}};a.prototype._createTocContent=function(){this._elTitleElementsLen=this.elTitleElements.length;if(!this._elTitleElementsLen){return;}this.tocContent="";
this._tempLists=[];var d=location.origin+location.pathname;for(var f=0;f<this._elTitleElementsLen;f++){var c=f+1;this._elTitleElement=this.elTitleElements[f];
this._elTitleElementName=this._elTitleElement.tagName;this._elTitleElementText=this._elTitleElement.innerHTML;this._elTitleElement.setAttribute("id","tip"+f);
this.tocContent+='<li><a href="'+d+"#tip"+f+'">'+this._elTitleElementText+"</a>";if(c!=this._elTitleElementsLen){this._elNextTitleElementName=this.elTitleElements[c].tagName;
if(this._elTitleElementName!=this._elNextTitleElementName){var h=false,g=1;for(var e=this._tempLists.length-1;e>=0;e--){if(this._tempLists[e].tagName==this._elNextTitleElementName){h=true;
break;}g++;}if(h){this.tocContent+=new Array(g+1).join("</li></ul>");this._tempLists.length=this._tempLists.length-g;}else{this._tempLists.push(this._elTitleElement);
this.tocContent+="<ul>";}}else{this.tocContent+="</li>";}}else{if(this._tempLists.length){this.tocContent+=new Array(this._tempLists.length+1).join("</li></ul>");
}else{this.tocContent+="</li>";}}}this.tocContent="<ul>"+this.tocContent+"</ul>";};a.prototype._showToc=function(){this.toc=document.createElement("div");
this.toc.innerHTML=this.tocContent;this.toc.setAttribute("class",this.tocClass);if(!this.options.targetId){this.el.appendChild(this.toc);}else{document.getElementById(this.options.targetId).appendChild(this.toc);
}var c=this;if(this.tocTop>-1){b.onscroll=function(){var d=document.documentElement.scrollTop||document.body.scrollTop;if(d<c.tocTop){c.toc.setAttribute("style","position:absolute;top:"+c.tocTop+"px;");
}else{c.toc.setAttribute("style","position:fixed;top:10px;");}};}};b.Toc=a;})(window);