如何用jQuery自动为文档生成带有锚点的目录(TOC)?
- 内容介绍
- 文章标签
- 相关推荐
本文共计149个文字,预计阅读时间需要1分钟。
javascript// 创建内容目录const contentDom=$('#content');
function createContentTOC(contentDom) { let tocBox=$('').attr('id', 'toc'); contentDom.prepend(tocBox);}
// contentDom = $('content') function createContentTOC(contentDom) { 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 = $('') let a = $('' + hTag.text() + '') 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() } example.html
内容结构
本文共计149个文字,预计阅读时间需要1分钟。
javascript// 创建内容目录const contentDom=$('#content');
function createContentTOC(contentDom) { let tocBox=$('').attr('id', 'toc'); contentDom.prepend(tocBox);}
// contentDom = $('content') function createContentTOC(contentDom) { 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 = $('') let a = $('' + hTag.text() + '') 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() } example.html
内容结构

