Last active
January 11, 2018 03:57
-
-
Save inhere/08a720b04b77bc8a1c47c08323b46061 to your computer and use it in GitHub Desktop.
简单快速给文档生成TOC(使用jQuery, 自动生成锚点,可添加 anchorIcon)
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
<style> | |
[data-anchor-icon]::after { | |
content: attr(data-anchor-icon); | |
} | |
</style> | |
<div id="content-toc-box"> | |
<div class="title"><i class="fa fa-list"></i> 内容结构</div> | |
<div id="content-toc"></div> | |
</div> | |
<div id="content" class="">文章内容...</div> | |
<script> | |
create_content_TOC($('#content'), {anchorIcon: '§'}) | |
</script> |
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
// contentDom = $('#content') | |
function create_content_TOC(contentDom, config) { | |
let tocBox = $('#content-toc-box'), | |
tocList = $("#content-toc"), | |
hList = contentDom.find("h2,h3,h4,h5,h6") | |
if (!hList[0]) { | |
tocBox.hide() | |
return | |
} | |
let haStyle = { | |
opacity: 0.65, | |
position: 'absolute', | |
marginLeft: '-1em', | |
paddingRight: '0.5em', | |
} | |
tocList.html('') | |
hList.each(function (i, item) { | |
let hTag = $(item), title = hTag.text() | |
let tag = hTag.get(0).localName | |
let id = 'md-title-item' + i | |
let mgLeft = (tag[1] - 2) * 15 | |
/* £ $ & β ξ ψ ℘ § */ | |
let ha = $('<a class="anchor-link" data-anchor-icon="' + config.anchorIcon + '"></a>') | |
let a = $('<a data-tag="' + tag + '" href="#' + id + '">' + hTag.text() + '</a>') | |
ha.attr('href', '#' + id).css(haStyle) | |
hTag.attr('id', id).addClass('content-htag').prepend(ha) | |
a.attr('title', title).addClass('toc-' + tag).css({ marginLeft: mgLeft, display: 'block' }) | |
tocList.append(a) | |
}) | |
tocBox.show() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment