解析 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);
    });
}

使用

css使用

.menu {
    position: fixed;
    top: 10%;
    right: 4%;
    border-left: 1px solid #ddd;
}

.menu a {
    color: rgb(21, 20, 20);
    text-decoration: none;
}

.menu a:hover {
    color: #eb5055;
}

.menu a::before {
    position: relative;
    top: 0;
    left: -4px;
    display: inline-block;
    width: 7px;
    height: 7px;
    content: '';
    border-radius: 50%;
    background-color: #eb5055;
}

@media screen and (max-width: 1300px) {
    .menu {
    display: none !important;
    }
}

Js

container 为我要解析的文章
menu 为渲染的节点

// 导入 jquery
create_content_TOC($(".container"), { class: '' }, $(".menu"))

结果

图片描述...

相关项目

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

Comments are closed.