12

解析 Html 自动生成目录 TOC 的相关代码

 3 years ago
source link: https://surest.cn/archives/170/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

解析 Html 自动生成目录 TOC 的相关代码

function create_content_TOC(dom, config, target) {
    let hList = dom.find('h1,h2,h3,h4,h5,h6');
    console.log(hList);
    target.html('');

    if (!hList[0]) {
        target.html('');
        target.hide();
        return;
    }

    target.show();
    let haStyle = {
        opacity: 0.65,
        position: 'absolute',
        marginLeft: '-1em',
        paddingRight: '0.5em'
    };

    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</a>"`);
        let a = $(`<a data-tag="${tag}" class="${tag == 'h1' ? '' : config.class}" 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' });
        console.log(a);
        target.append(a);
    });
}
![图片描述...](https://cdn.surest.cn/Fhz0wFFlvINnM661E9-MKZYobxzC)

https://github.com/posthtml/posthtml-toc

本文由 邓尘锋 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: May 8, 2021 at 11:09 am


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK