首页 > 其他 > 详细

给博客园添加目录

时间:2019-12-29 16:05:12      阅读:77      评论:0      收藏:0      [点我收藏+]

给博客园添加目录

目录如上所示

原理

  1. 将博客园所生成的博客HTML中的标题元素(h1~h6)检出
  2. 根据目录等级生成目录树
  3. 根据目录树生成HTML代码
  4. 插入到适当位置

代码

/**
 * 获取 #cnblogs_post_body 元素下的标题元素
 * 返回标题的数组
 * @returns [{tagName:'H1',text:'title',id:'title'},...]
 */
function getHeadsFromPost() {
    var c = document.getElementById('cnblogs_post_body').children;
    var data = [];
    for (var i = 0; i < c.length; i++) {
        if (/h\d/i.test(c[i].tagName)) {
            data.push({ tagName: c[i].tagName, text: c[i].innerText, id: c[i].id });
        }
    }
    return data;
}
/**
 * 将标题的数组转换成树的结构
 */
function arr2Tree(arr) {
    var tree = [];
    tree.pushlast = function (n) {
        if (this[this.length - 1].children) {
            this[this.length - 1].children.push(n);
        } else {
            this[this.length - 1].children = [n];
        }
    }
    tree.empty = function () { return this.length === 0; }
    tree.last = function () { return this[this.length - 1]; }
    arr.forEach(head => {
        if (tree.empty() || head.tagName <= tree.last().tagName) {
            tree.push(head);
        } else {
            tree.pushlast(head)
        }
    })
    tree.forEach(head => { if (head.children) head.children = arr2Tree(head.children) });
    return tree;
}
/**
 * 根据树的结构生成HTML
 */
function createHTML(data) {
    function head2li(head) {
        var html = `<li><a href='#${head.id}'>${head.text}</a></li>`;
        if (head.children) {
            html += arr2html(head.children);
        }
        return html;
    }
    function arr2html(arr) {
        return `<ul>${arr.map(head2li).join('')}</ul>`;
    }
    return arr2html(data);
}
/**
 * 插入HTML
 */
function insert2PostBody(contenthtml) {
    var content = document.createElement('div');
    content.id = 'custom-content';
    content.innerHTML = contenthtml;
    document.getElementById('cnblogs_post_body').prepend(content);
}
/**
 * 自动生成目录
 */
function createContent() {
    var rawdata = getHeadsFromPost();
    var treedata = arr2Tree(rawdata);
    var contenthtml = createHTML(treedata);
    insert2PostBody(contenthtml);
}
createContent();

给博客园添加目录

原文:https://www.cnblogs.com/bfjdbcs/p/12115098.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!