查看簡書文章時,自動生成側邊目錄

安裝 chrome 插件——油猴腳本(Tampermonkey)

下載方式

  • Chrome 應用商店下載
    • 進入 Chrome 應用商店, 搜索 Tampermonkey 安裝即可
  • 官網下載
    • 進入官網
    • 打開擴展程序的開發(fā)者模式,點擊 "加載已解壓的擴展程序",找到你下載的插件的 exe 文件,安裝即可
    • 成功安裝后,可以在瀏覽器的右上角顯示油猴的圖標

添加腳本

  • 點擊瀏覽器右上角的油猴圖標, 在下拉框中選擇 "添加新腳本..."
  • 將下面的代碼覆蓋腳本代碼, Ctrl + S 保存
// ==UserScript==
// @name                自動生成簡書文章目錄
// @namespace           create-catalog
// @version             1.3
// @author              2024
// @description         給簡書增加目錄功能(通過識別h1-h6標題,自動生成目錄放于頁面的左側)
// @match               http://www.itdecent.cn/p/*
// @match               http://www.itdecent.cn/p/*
// @grant               none
// @require             https://cdn.bootcss.com/jquery/3.4.1/jquery.js
// @require             https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js

// ==/UserScript==

var version = 1;

// 獲取簡書閱讀模式
function getReadMode(){
    return $.cookie('read_mode') || 'day'
}

// 獲取樣式風格
function getStyle(){
    if(getReadMode() === 'day'){
        return {
            background: 'white',
            color: 'black'
        }
    } else {
        return {
            background:'#3d3d3d',
            color:'#b3b3b3'
        }
    }
}

//去除字符串所有空格
function trim (str, is_global) {
    var result;
    result = str.replace(/(^\s+)|(\s+$)/g, "");
    if (is_global&&is_global.toLowerCase() == "g") {
        result = result.replace(/\s/g, "");
    }
    return result;
}

//轉義尖括號
function toTxt(str) {
    var RexStr = /\<|\>/g
    str = str.replace(RexStr, function(MatchStr) {
        switch (MatchStr) {
            case "<":
                return "&lt;";
                break;
            case ">":
                return "&gt;";
                break;
            default:
                break;
        }
    })
    return str;
}
var menuIndex = 0; //初始化標題索引

// 在側邊欄中添加目錄項
function appendMenuItem(tagName,id,content) {
    let paddingLeft = tagName.substring(1) * 10; //添加標題縮進
    let style = getStyle();
    $('#menu_nav_ol').append(`<li class="${id}" style="padding-left: ${paddingLeft}px;line-height:40px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;max-width: 200px"><a href=javascript:; title="${toTxt(trim(content,"g"))}" style="color:${style.color}">${content}</a></li>`);
}

(function() {
    // 獲取標題元素
    let titles = $('body article').find('h1,h2,h3,h4,h5,h6');
    let style = getStyle();

    if(titles.length === 0) {
        return;
    }
    // 將文章內容右移
    // 在 body 標簽內部添加 aside 側邊欄,用于顯示文檔目錄
    let asideContent = `<aside id="sideMenu" style="font-size:15px;color:${style.color};position: fixed;padding: 20px 15px 20px 0;top: 66px;left: 10px;margin-bottom:20px;background-color: ${style.background};z-index: 810;overflow-y: auto;height:calc(100% - 124px);border-radius:4px"></aside>`;
    $('body').prepend(asideContent);
    $('#sideMenu').append('<ol id="menu_nav_ol" style="list-style:none;margin:0px;padding:0 0 0 10px">');// 不顯示 li 項前面默認的點標志, 也不使用默認縮進
    $('div[role="main"]').css('paddingLeft','160px');

    // 遍歷文章中的所有標題行, 按需添加id值, 并增加記錄到目錄列表中
    titles.each(function() {
        let tagName = $(this)[0].tagName.toLocaleLowerCase();
        let content = $(this).text();
        // 若標題的id不存在,則使用新id
        let newTagId =$(this).attr('id');

        if(content){
            if(!$(this).attr('id')) {
                newTagId = 'id_'+menuIndex;
                $(this).attr('id',newTagId);
                $(this).addClass('main-title')
                menuIndex++;
            }
            appendMenuItem(tagName,newTagId,content);

        }

    });

    $('#sideMenu').append('</ol>');

    if(!$('#menu_nav_ol li').length){
        $('#sideMenu').remove()
    }
    // 綁定目錄li點擊事件,點擊時跳轉到對應的位置
    $('#menu_nav_ol li').on('click',function() {
        let targetId = $(this).attr('class');
        var _top=$("#"+targetId).offset().top-75
        $('html,body').animate({
            scrollTop:_top
        }, 300);
    });
    //滾動頁面增加左側菜單高亮
    var active=function(){
        var scrollTop=$(window).scrollTop();
        $('.main-title').each(function(i){
            if(i<$('.main-title').length-1){
                if(scrollTop+76>=$(this).offset().top&&scrollTop+76<$('.main-title').eq(i+1).offset().top){
                    $('#sideMenu li a').css({color: style.color});
                    $('#sideMenu li').eq(i).find('a').css({color:'#61aeee'});
                    $('#sideMenu li').css({borderLeft:'0'})
                    $('#sideMenu li').eq(i).css({borderLeft:'5px solid #61aeee'});
                }
            }else{
                if(scrollTop+76>=$(this).offset().top){
                    $('#sideMenu li a').css({color: style.color});
                    $('#sideMenu li').eq(i).find('a').css({color:'#61aeee'});
                    $('#sideMenu li').css({borderLeft:'0'})
                    $('#sideMenu li').eq(i).css({borderLeft:'5px solid #61aeee'});
                }
            }

        })

    }
    active()
    var timer=null;
    $(window).scroll(function(){
        clearTimeout(timer)
        timer=setTimeout(function(){
            active()
        },10)

    })
})();

完成

刷新頁面, 看下效果~

不需要目錄時,只需把腳本按鈕關閉即可

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容