簡(jiǎn)書markdown如何實(shí)現(xiàn)側(cè)邊目錄

效果圖

??效果大概如下圖所示


效果圖.png

??本來(lái)markdown語(yǔ)法是支持標(biāo)題生成目錄的征绎,但是簡(jiǎn)書的并沒(méi)有支持蹲姐。所以就想到用腳本解決了。

方法

1人柿、谷歌瀏覽器安裝tampermonkey

??一柴墩、官網(wǎng):http://www.tampermonkey.net/
??二、如果嫌速度太慢的話顷扩,就離線安裝鏈接:??https://pan.baidu.com/s/1y5J6S5SpwbKWbz3Zu0GLlg
??提取碼:ezse
??方法:
(1) 從設(shè)置->更多工具->擴(kuò)展程序 打開擴(kuò)展程序頁(yè)面拐邪,或者地址欄輸入 chrome://extensions/ 按下回車打開擴(kuò)展程序頁(yè)面

打開擴(kuò)展程序頁(yè)面

(2) 打開擴(kuò)展程序頁(yè)面的“開發(fā)者模式”
打開開發(fā)者模式

(3) 將crx文件拖拽到擴(kuò)展程序頁(yè)面,完成安裝
完成安裝

2隘截、clone腳本

打開添加腳本頁(yè)面

下面腳本來(lái)自GitHub lxx2013/utils

// ==UserScript==
// @name         簡(jiǎn)書網(wǎng)站左側(cè)目錄生成
// @namespace    http://tampermonkey.net/
// @version      1.0.0
// @description  簡(jiǎn)書網(wǎng)站左側(cè)目錄生成,支持非h1標(biāo)題,支持滾動(dòng)
// @author       https://github.com/lxx2013
// @match        http://www.reibang.com/p/*
// @match        http://www.reibang.com/p/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';
    initSidebar('.sidebar', '.post');
})();

/**
* 簡(jiǎn)書網(wǎng)站左側(cè)目錄生成插件
* 代碼參考了 https://github.com/vuejs/vuejs.org/blob/master/themes/vue/source/js/common.js
* @param {string} sidebarQuery - 目錄 Element 的 query 字符串 
* @param {string} contentQuery - 正文 Element 的 query 字符串
*/
function initSidebar(sidebarQuery, contentQuery) {
    addAllStyle()
    var body = document.body
    var sidebar = document.querySelector(sidebarQuery)
    // 在 body 標(biāo)簽內(nèi)部添加 div.sidebar 側(cè)邊欄,用于顯示文檔目錄
    if (!sidebar) {
        sidebar = document.createElement('div')
        body.insertBefore(sidebar, body.firstChild)
    }
    sidebar.classList.add('sidebar')
    var content = document.querySelector(contentQuery)
    if (!content) {
        throw ('Error: content not find!')
        return
    }
    content.classList.add('content-with-sidebar');
    var ul = document.createElement('ul')
    ul.classList.add('menu-root')
    sidebar.appendChild(ul)

    var allHeaders = []
    // 遍歷文章中的所有 h1或 h2(取決于最大的 h 是多大) , 編輯為li.h3插入 ul
    //因?yàn)闃?biāo)題一定是 h1 所以優(yōu)先處理,然后再看文章正文部分是以 h1作為一級(jí)標(biāo)題還是 h2或 h3作為一級(jí)標(biāo)題
    //采用的方法是優(yōu)先遍歷正文, 然后再插入標(biāo)題這個(gè)h1
    var i = 1
    var headers = [].slice.call(content.querySelectorAll('h' + i++), 1)
    while (!headers.length && i <= 6) {
        headers = Array.from(content.querySelectorAll('h' + i++))
    }
    [].unshift.call(headers, content.querySelector('h1'))
    if (headers.length) {
        [].forEach.call(headers, function (h) {
            var h1 = makeLink(h, 'a', 'h1-link')
            ul.appendChild(h1)
            allHeaders.push(h)
            //尋找h1的子標(biāo)題
            var h2s = collectHs(h)
            if (h2s.length) {
                [].forEach.call(h2s, function (h2) {
                    allHeaders.push(h2)
                    var h3s = collectHs(h2)
                    h2 = makeLink(h2, 'a', 'h2-link')
                    ul.appendChild(h2)
                    //再尋找 h2 的子標(biāo)題 h3
                    if (h3s.length) {
                        var subUl = document.createElement('ul')
                        subUl.classList.add('menu-sub')
                        h2.appendChild(subUl)
                            ;[].forEach.call(h3s, function (h3) {
                                allHeaders.push(h3)
                                h3 = makeLink(h3, 'a', 'h3-link')
                                subUl.appendChild(h3)
                            })
                    }
                })
            }
        })
    }
    //增加 click 點(diǎn)擊處理,使用 scrollIntoView,增加控制滾動(dòng)的 flag
    var scrollFlag = 0
    var scrollFlagTimer
    sidebar.addEventListener('click', function (e) {
        e.preventDefault()
        if (e.target.href) {
            scrollFlag = 1
            clearTimeout(scrollFlagTimer)
            scrollFlagTimer = setTimeout(() => scrollFlag = 0, 1500)
            setActive(e.target, sidebar)
            var target = document.getElementById(e.target.getAttribute('href').slice(1))
            target.scrollIntoView({ behavior: 'smooth', block: "center" })
        }
    })
    //監(jiān)聽窗口的滾動(dòng)和縮放事件
    window.addEventListener('scroll', updateSidebar)
    window.addEventListener('resize', throttle(updateSidebar))
    function updateSidebar() {
        if (scrollFlag)
            return
        var doc = document.documentElement
        var top = doc && doc.scrollTop || document.body.scrollTop
        if (!allHeaders.length) return
        var last
        for (var i = 0; i < allHeaders.length; i++) {
            var link = allHeaders[i]
            if (link.offsetTop > (top + document.body.clientHeight / 2 - 73)) {
                if (!last) { last = link }
                break
            } else {
                last = link
            }
        }
        if (last) {
            setActive(last.id, sidebar)
        }
    }
}

/**
>為正文的標(biāo)題創(chuàng)建一個(gè)對(duì)應(yīng)的錨,返回的節(jié)點(diǎn)格式為`<li><tag class="className"> some text </tag><li>`
@param {HTMLElement} h - 需要在目錄中為其創(chuàng)建鏈接的一個(gè)標(biāo)題,它的`NodeType`可能為`H1 | H2 | H3`
@param {string} tag - 返回的 li 中的節(jié)點(diǎn)類型, 默認(rèn)為 a
@param {string} className - 返回的 tag 的 class ,默認(rèn)為空
@returns {HTMLElement} 返回的節(jié)點(diǎn)格式為`<li><a> some text </a><li>`
*/
function makeLink(h, tag, className) {
    tag = tag || 'a'
    className = className || ''
    var link = document.createElement('li')
    var text = [].slice.call(h.childNodes).map(function (node) {
        if (node.nodeType === Node.TEXT_NODE) {
            return node.nodeValue
        } else if (['CODE', 'SPAN', 'A'].indexOf(node.tagName) !== -1) {
            return node.textContent
        } else {
            return ''
        }
    }).join('').replace(/\(.*\)$/, '')
    if (!h.id) h.id = IdEscape(text)
    link.innerHTML =
        `<${tag} class="${className}" href="#${h.id}">${htmlEscape(text)}</${tag}>`
    return link
}

/**
*對(duì) id 進(jìn)行格式化.把空白字符和引號(hào)轉(zhuǎn)義為下劃線
*>注意:id值使用字符時(shí)扎阶,除了 ASCII字母和數(shù)字、“—”婶芭、“-"东臀、"."之外,可能會(huì)引起兼容性問(wèn)題犀农,因?yàn)樵贖TML4中是不允許包含這些字符的惰赋,這個(gè)限制在HTML5中更加嚴(yán)格,為了兼容性id值必須由字母開頭,同時(shí)不允許其中有空格。參考https://developer.mozilla.org/zh-CN/docs/Web/HTML/Global_attributes/id
*>但是本程序中使用了 document.getElementById 的要求稍放寬了一些,"#3.1_createComponent"這樣的 id能成功執(zhí)行
@param {string} text - HTML特殊字符
@returns {string} 轉(zhuǎn)義后的字符串,例如`# 1'2"3標(biāo)題`被轉(zhuǎn)義為`#_1_2_3標(biāo)題`
*/
function IdEscape(text) {
    return text.replace(/[\s"']/g, '_') //注意這里不加 g 的話就會(huì)只匹配第一個(gè)匹配,所以會(huì)出錯(cuò)
}
/**
>HTML 特殊字符[ &, ", ', <, > ]轉(zhuǎn)義
@param {string} text - HTML特殊字符
@returns {string} 轉(zhuǎn)義后的字符,例如`<`被轉(zhuǎn)義為`&lt`
*/
function htmlEscape(text) {
    return text
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
}
/**
*為一個(gè) `h(x)`標(biāo)題節(jié)點(diǎn)收集跟在它屁股后面的 `h(x+1)`標(biāo)題節(jié)點(diǎn),
>若屁股后面沒(méi)有`h(x+1)`節(jié)點(diǎn),則收集`h(x+2)`節(jié)點(diǎn)甚至`h(x+3)`,畢竟不知道文章作者喜歡用哪種大小做標(biāo)題
>收集過(guò)程中若遇到 `h(x)或h(x-1)`節(jié)點(diǎn)的話要立即返回
@param {HTMLElement}  h - HTML 標(biāo)題節(jié)點(diǎn) `H1~H6`
@returns {HTMLElement[]} 一個(gè)由 h(x+1)或 h(x+2)等后代目錄節(jié)點(diǎn)組成的數(shù)組
*/
function collectHs(h) {
    var childIndexes = []
    var thisTag = h.tagName
    var count = 1
    do {
        var childTag = h.tagName[0] + (parseInt(h.tagName[1]) + count++)
        var next = h.nextElementSibling
        while (next) {
            if (next.tagName[0] == 'H' && next.tagName[1] <= thisTag[1]) {
                break
            }
            else if (next.tagName === childTag) {
                childIndexes.push(next)
            }
            next = next.nextElementSibling
        }
    } while (childTag < 'H6' && childIndexes.length == 0)
    return childIndexes
}
/**
*設(shè)置目錄的激活狀態(tài),按既定規(guī)則添加 active 和 current 類
*>無(wú)論對(duì)h2還是 h3進(jìn)行操作,首先都要移除所有的 active 和 current 類, 然后對(duì) h2添加 active 和 current, 或?qū)?h3添加 active 對(duì)其父目錄添加 current
@param {String|HTMLElement}  id - HTML標(biāo)題節(jié)點(diǎn)或 querySelector 字符串
@param {HTMLElement} sidebar - 邊欄的 HTML 節(jié)點(diǎn)
*/
function setActive(id, sidebar) {
    //1.無(wú)論對(duì)h2還是 h3進(jìn)行操作,首先都要移除所有的 active 和 current 類, 
    var previousActives = sidebar.querySelectorAll(`.active`)
        ;[].forEach.call(previousActives, function (h) {
            h.classList.remove('active')
        })
    previousActives = sidebar.querySelectorAll(`.current`)
        ;[].forEach.call(previousActives, function (h) {
            h.classList.remove('current')
        })
    //獲取要操作的目錄節(jié)點(diǎn)
    var currentActive = typeof id === 'string'
        ? sidebar.querySelector('a[href="#' + id + '"]')
        : id
    if (currentActive.classList.contains('h2-link') != -1) {
        //2. 若為 h2,則添加 active 和 current
        currentActive.classList.add('active', 'current')
    }
    if ([].indexOf.call(currentActive.classList, 'h3-link') != -1) {
        //3. 若為 h3,則添加 active 且對(duì)其父目錄添加 current
        currentActive.classList.add('active')
        var parent = currentActive
        while (parent && parent.tagName != 'UL') {
            parent = parent.parentNode
        }
        parent.parentNode.querySelector('.h2-link').classList.add('current', 'active')
    }
    //左側(cè)目錄太長(zhǎng)時(shí)的效果
    currentActive.scrollIntoView({ behavior: 'smooth' })
}
/**
>增加 sidebar 需要的全部樣式
@param {string} highlightColor - 高亮顏色, 默認(rèn)為'#c7254e'
*/
function addAllStyle(highlightColor) {
    highlightColor = highlightColor || "#c7254e"
    var sheet = newStyleSheet()
    /**
    >創(chuàng)建一個(gè)新的`<style></style>`標(biāo)簽插入`<head>`中
    @return {Object} style.sheet,`它具有方法insertRule`
    */
    function newStyleSheet() {
        var style = document.createElement("style");
        // 對(duì)WebKit hack :(
        style.appendChild(document.createTextNode(""));
        // 將 <style> 元素加到頁(yè)面中
        document.head.appendChild(style);
        return style.sheet;
    }
    var position = 0
    /**
    >添加一條 css 規(guī)則
    @param {string} str - css樣式,也可以是@media
    */
    function addStyle(str) {
        sheet.insertRule(str,position++);
    }
    addStyle(`.sidebar{position:fixed;    z-index: 10;
        top: 61px;
        left: 0;
        bottom: 0;
        overflow-x: hidden;
        overflow-y: auto;
        padding: 40px 20px 60px 30px;
        max-width: 310px;
    }`)
    addStyle(`.menu-root { list-style:none; text-align:left }`)
    addStyle(`.menu-root .h1-link{
        display:inline-block;
        color:rgb(44, 62, 80);
        font-family:"source sans pro", "helvetica neue", Arial, sans-serif;
        font-size:17.55px;
        font-weight:600;
        height:22px;
        line-height:22.5px;
        list-style-type:none;
        margin-block-end:11px;
        margin-block-start:11px;
    }`)
    addStyle(`.menu-root .h2-link:hover {
        border-bottom: 2px solid ${highlightColor};
    }`)
    addStyle(`.menu-root .h2-link.current+.menu-sub{
        display:block;
    }`)
    addStyle(`.menu-root .h2-link{
        color:rgb(127,140,141);
        cursor:pointer;
        font-family:"source sans pro", "helvetica neue", Arial, sans-serif;
        font-size:15px;
        height:auto;
        line-height:22.5px;
        list-style-type:none;
        text-align:left;
        text-decoration-color:rgb(127, 140, 141);
        text-decoration-line:none;
        text-decoration-style:solid;
        margin-left:12.5px;
    }`)
    addStyle(`.menu-sub {
        padding-left:25px;
        list-style:none;
        display:none;
    }`)
    addStyle(`.menu-sub .h3-link{
        color:#333333;
        cursor:pointer;
        display:inline;
        font-family:"source sans pro", "helvetica neue", Arial, sans-serif;
        font-size:12.75px;
        height:auto;
        line-height:19.125px;
        list-style-type:none;
        text-align:left;
        text-decoration-color:rgb(52, 73, 94);
        text-decoration-line:none;
        text-decoration-style:solid;
    }`)
    addStyle(`@media only screen and (max-width : 1300px){
        .content-with-sidebar {
            margin-left:310px !important;
        }
    }`)
    addStyle(`.sidebar .active{
        color:${highlightColor};
        font-weight:700;
    }`)
}
/**
>函數(shù)節(jié)流
>參考https://juejin.im/entry/58c0379e44d9040068dc952f
@param {Fuction} fn - 要執(zhí)行的函數(shù)
*/
function throttle(fn, interval = 300) {
    let canRun = true;
    return function () {
        if (!canRun) return;
        canRun = false;
        setTimeout(() => {
            fn.apply(this, arguments);
            canRun = true;
        }, interval);
    };
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末赁濒,一起剝皮案震驚了整個(gè)濱河市轨奄,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌拒炎,老刑警劉巖挪拟,帶你破解...
    沈念sama閱讀 219,366評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異击你,居然都是意外死亡玉组,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門丁侄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)惯雳,“玉大人,你說(shuō)我怎么就攤上這事鸿摇∈埃” “怎么了?”我有些...
    開封第一講書人閱讀 165,689評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵拙吉,是天一觀的道長(zhǎng)鸵钝。 經(jīng)常有香客問(wèn)我,道長(zhǎng)庐镐,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,925評(píng)論 1 295
  • 正文 為了忘掉前任变逃,我火速辦了婚禮必逆,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘揽乱。我一直安慰自己名眉,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評(píng)論 6 392
  • 文/花漫 我一把揭開白布凰棉。 她就那樣靜靜地躺著损拢,像睡著了一般。 火紅的嫁衣襯著肌膚如雪撒犀。 梳的紋絲不亂的頭發(fā)上福压,一...
    開封第一講書人閱讀 51,727評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音或舞,去河邊找鬼荆姆。 笑死,一個(gè)胖子當(dāng)著我的面吹牛映凳,可吹牛的內(nèi)容都是我干的胆筒。 我是一名探鬼主播,決...
    沈念sama閱讀 40,447評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼诈豌,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼仆救!你這毒婦竟也來(lái)了抒和?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,349評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤彤蔽,失蹤者是張志新(化名)和其女友劉穎摧莽,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體铆惑,經(jīng)...
    沈念sama閱讀 45,820評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡范嘱,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了员魏。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片丑蛤。...
    茶點(diǎn)故事閱讀 40,127評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖撕阎,靈堂內(nèi)的尸體忽然破棺而出受裹,到底是詐尸還是另有隱情,我是刑警寧澤虏束,帶...
    沈念sama閱讀 35,812評(píng)論 5 346
  • 正文 年R本政府宣布棉饶,位于F島的核電站,受9級(jí)特大地震影響镇匀,放射性物質(zhì)發(fā)生泄漏照藻。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評(píng)論 3 331
  • 文/蒙蒙 一汗侵、第九天 我趴在偏房一處隱蔽的房頂上張望幸缕。 院中可真熱鬧,春花似錦晰韵、人聲如沸发乔。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)栏尚。三九已至,卻和暖如春只恨,著一層夾襖步出監(jiān)牢的瞬間译仗,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工坤次, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留古劲,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,388評(píng)論 3 373
  • 正文 我出身青樓缰猴,卻偏偏與公主長(zhǎng)得像产艾,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評(píng)論 2 355