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

in 其他 with 0 comment

解析 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

Comments are closed.