当前位置 : 主页 > 网络编程 > JavaScript >

给文档生成TOC(使用jQuery,自动生成锚点)

来源:互联网 收集:自由互联 发布时间:2021-06-30
create_content_toc.js // 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
create_content_toc.js
// 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
 
	
  
    内容结构
  
	

 

网友评论