簡書文章左側目錄(帶滾動)

前言

簡書有一不太方便的一點就是沒有左側目錄。所以自己定製給簡書的博客自動生成側邊目錄。

參考了簡書博客hexo-theme-vue
但上述2個效果腳本都比較簡單,我額外添加了滾動效果, 以及對非 h1 起頭的標題的識別. 另外完善了註釋

先看效果:

image

生成目錄方法

1. 安裝 Tampermonkey

從chrome網上應用商店搜到安裝就好

2. 點擊添加新腳本:

image

3. 在編輯器裏寫腳本爲頁面添加側邊目錄。

image

4.保存

圖片.png

代碼

// ==UserScript==
// @name         簡書網站左側目錄生成
// @namespace    http://tampermonkey.net/
// @version      1.0.0
// @description  簡書網站左側目錄生成,支持非h1標題,支持滾動
// @author       https://github.com/lxx2013
// @match        http://www.jianshu.com/p/*
// @match        https://www.jianshu.com/p/*
// @grant        none
// ==/UserScript==

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

/**
* 簡書網站左側目錄生成插件
* 代碼參考了 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 標籤內部添加 div.sidebar 側邊欄,用於顯示文檔目錄
    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
    //因爲標題一定是 h1 所以優先處理,然後再看文章正文部分是以 h1作爲一級標題還是 h2或 h3作爲一級標題
    //採用的方法是優先遍歷正文, 然後再插入標題這個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的子標題
            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 的子標題 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 點擊處理,使用 scrollIntoView,增加控制滾動的 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" })
        }
    })
    //監聽窗口的滾動和縮放事件
    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)
        }
    }
}

/**
>爲正文的標題創建一個對應的錨,返回的節點格式爲`<li><tag class="className"> some text </tag><li>`
@param {HTMLElement} h - 需要在目錄中爲其創建鏈接的一個標題,它的`NodeType`可能爲`H1 | H2 | H3`
@param {string} tag - 返回的 li 中的節點類型, 默認爲 a
@param {string} className - 返回的 tag 的 class ,默認爲空
@returns {HTMLElement} 返回的節點格式爲`<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
}

/**
*對 id 進行格式化.把空白字符和引號轉義爲下劃線
*>注意:id值使用字符時,除了 ASCII字母和數字、“—”、“-"、"."之外,可能會引起兼容性問題,因爲在HTML4中是不允許包含這些字符的,這個限制在HTML5中更加嚴格,爲了兼容性id值必須由字母開頭,同時不允許其中有空格。參考https://developer.mozilla.org/zh-CN/docs/Web/HTML/Global_attributes/id
*>但是本程序中使用了 document.getElementById 的要求稍放寬了一些,"#3.1_createComponent"這樣的 id能成功執行
@param {string} text - HTML特殊字符
@returns {string} 轉義後的字符串,例如`# 1'2"3標題`被轉義爲`#_1_2_3標題`
*/
function IdEscape(text) {
    return text.replace(/[\s"']/g, '_') //注意這裏不加 g 的話就會只匹配第一個匹配,所以會出錯
}
/**
>HTML 特殊字符[ &, ", ', <, > ]轉義
@param {string} text - HTML特殊字符
@returns {string} 轉義後的字符,例如`<`被轉義爲`&lt`
*/
function htmlEscape(text) {
    return text
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
}
/**
*爲一個 `h(x)`標題節點收集跟在它屁股後面的 `h(x+1)`標題節點,
>若屁股後面沒有`h(x+1)`節點,則收集`h(x+2)`節點甚至`h(x+3)`,畢竟不知道文章作者喜歡用哪種大小做標題
>收集過程中若遇到 `h(x)或h(x-1)`節點的話要立即返回
@param {HTMLElement}  h - HTML 標題節點 `H1~H6`
@returns {HTMLElement[]} 一個由 h(x+1)或 h(x+2)等後代目錄節點組成的數組
*/
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
}
/**
*設置目錄的激活狀態,按既定規則添加 active 和 current 類
*>無論對h2還是 h3進行操作,首先都要移除所有的 active 和 current 類, 然後對 h2添加 active 和 current, 或對 h3添加 active 對其父目錄添加 current
@param {String|HTMLElement}  id - HTML標題節點或 querySelector 字符串
@param {HTMLElement} sidebar - 邊欄的 HTML 節點
*/
function setActive(id, sidebar) {
    //1.無論對h2還是 h3進行操作,首先都要移除所有的 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')
        })
    //獲取要操作的目錄節點
    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 且對其父目錄添加 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')
    }
    //左側目錄太長時的效果
    currentActive.scrollIntoView({ behavior: 'smooth' })
}
/**
>增加 sidebar 需要的全部樣式
@param {string} highlightColor - 高亮顏色, 默認爲'#c7254e'
*/
function addAllStyle(highlightColor) {
    highlightColor = highlightColor || "#c7254e"
    var sheet = newStyleSheet()
    /**
    >創建一個新的`<style></style>`標籤插入`<head>`中
    @return {Object} style.sheet,`它具有方法insertRule`
    */
    function newStyleSheet() {
        var style = document.createElement("style");
        // 對WebKit hack :(
        style.appendChild(document.createTextNode(""));
        // 將 <style> 元素加到頁面中
        document.head.appendChild(style);
        return style.sheet;
    }
    var position = 0
    /**
    >添加一條 css 規則
    @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;
    }`)
}
/**
>函數節流
>參考https://juejin.im/entry/58c0379e44d9040068dc952f
@param {Fuction} fn - 要執行的函數
*/
function throttle(fn, interval = 300) {
    let canRun = true;
    return function () {
        if (!canRun) return;
        canRun = false;
        setTimeout(() => {
            fn.apply(this, arguments);
            canRun = true;
        }, interval);
    };
}

代碼來源

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章