掘金小冊沒有目錄, 有時候看比較長的文章時, 很蛋疼.css
首先須要瀏覽器安裝Tampermonkeyjquery
左鍵點擊Tampermonkey, 出來如圖所示選項 瀏覽器
點擊管理面板
再點擊
+
號
粘貼以下代碼到編輯區bash
// ==UserScript==
// @name 掘金小冊目錄
// @description:zh-cn 自動生成掘金小冊目錄
// @namespace https://juejin.im/book/*
// @version 1.0
// @description create content
// @author Simon
// @match https://juejin.im/book/*
// @require https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js
// @grant none
// ==/UserScript==
var menuIndex = 0;
(function() {
'use strict';
init();
})();
function init() {
var a = setInterval(() => {
var content = document.getElementsByClassName('article-content');
if(content){
window.clearInterval(a);
initSidebar();
}
}, 1000);
}
function initSidebar() {
let titles = $('.article-content').find('h1,h2,h3,h4,h5,h6');
console.log(titles.length)
if(titles.length === 0){
return;
}
let contentHeight = window.innerHeight;
let asideContent = '<aside id="sideMenu" style="position: fixed;padding: 0px 15px 20px 0px;top: 0;right: 0;margin-bottom:20px;background-color: #eee;background-color: #eee;z-index: 810;overflow: scroll;max-height:'+contentHeight+'px;min-height:'+contentHeight+'px;min-width:200px;max-width:300px;"><h2 style="padding-left:30px">目錄<h2></aside>';
$('.book-content').prepend(asideContent);
$('#sideMenu').append('<ol id="menu_nav_ol" style="list-style:none;margin:0px;padding:0px;">');
titles.each(function(){
let tagName = $(this)[0].tagName.toLocaleLowerCase();
let content = $(this).text();
let newTagId =$(this).attr('id');
if(!$(this).attr('id')){
newTagId = 'id_'+menuIndex;
$(this).attr('id',newTagId);
menuIndex++;
}
if(newTagId !=='id_0')
appendMenuItem(tagName,newTagId,content);
});
$('#sideMenu').append('</ol>');
$('#menu_nav_ol li').on('click',function(){
let targetId = $(this).attr('class');
$(this).first().children("a").first().css('color', 'red');
$("#"+targetId)[0].scrollIntoView({behavior: "instant", block: "center", inline: "nearest"});
$('#menu_nav_ol').children().each(function(){
let otherId = $(this).attr('class');
if (targetId != otherId) {
$(this).first().children("a").first().css('color', 'black');
}
});
});
}
function appendMenuItem(tagName,id,content){
let paddingLeft = tagName.substring(1) * 20;
$('#menu_nav_ol').append('<li class="' + id +'" style="padding-left: '+ paddingLeft +'px;margin:10px 0"><a style="color:black;font-weight:bold">' + content + '</a></li>');
}
複製代碼
而後點擊文件
=> 保存
app
再次刷新便可, 效果以下:ide