Created
September 12, 2018 13:43
-
-
Save akkuman/7899a97bf8c92357927333e8788ba56d to your computer and use it in GitHub Desktop.
[生成目录.js] 动态生成h2,h3目录 #javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let genToc = function() { | |
let tor_tree = document.createElement('div'); | |
tor_tree.id = 'torTree'; | |
tor_tree.innerHTML += ' <h4 id="anchor-0">导航树</h4>'; | |
$(":header").each(function(index, element) { | |
let tag_name = $(this)[0].tagName; | |
let tag_a_html = ''; | |
if (tag_name == 'H2'||tag_name == 'H3') { | |
let anchor_text = 'anchor-'+(index+1); | |
$(this).attr('id', anchor_text); | |
tag_a_html += '<a href="#' + anchor_text + '"><span id="toc-' + anchor_text + '" class="tor' + 'i'.repeat(parseInt(tag_name.substr(-1,1))-1) + '">' + $(this)[0].innerText + '</span><br></a>'; | |
} | |
tor_tree.innerHTML += tag_a_html; | |
}); | |
$('.toc').append(tor_tree.outerHTML); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment