學子 CH python學習筆記之目錄自動生成
準備工具:瀏覽器chrome
步驟:
- ,安裝油候(tampermonkey)插件,具體方法參考網(wǎng)上的文章 油候安裝
- 點擊插件,點擊添加腳本,復制下文的代碼
- 保存
- 進入簡書,點擊文章(隨意即可)
// ==UserScript==
// @name 自動生成簡書目錄
// @namespace http://www.itdecent.cn/p/3f07f8f6159f
// @version 1.0
// @author 匿名的好人
// @match http://www.itdecent.cn/p/*
// @match http://www.itdecent.cn/p/*
// @grant none
// ==/UserScript==
var menuIndex = 0; //初始化標題索引
// 在側(cè)邊欄中添加目錄項
function appendMenuItem(tagName,id,content) {
console.log(tagName+" "+tagName.substring(1));
let paddingLeft = tagName.substring(1) * 20; //添加標題縮進
$('#menu_nav_ol').append('<li class="' + id + '" style="padding-left: '+ paddingLeft +'px;"><b>' + content + '</b></li>');
}
(function() {
'use strict';
// 使文章區(qū)域?qū)挾冗m配屏幕
let wider = $('.note').width() - 400;
let oriWidth = $('.post').width();
console.log(wider);
console.log(oriWidth);
if (wider < oriWidth) {
wider = oriWidth;
}
// 適配寬度
$('.post').width(wider);
// 保存標題元素
let titles = $('body').find('h1,h2,h3,h4,h5,h6');
if(titles.length === 0) {
return;
}
// 將文章內(nèi)容右移
$('.post').css('padding-left','200px');
// 在 body 標簽內(nèi)部添加 aside 側(cè)邊欄,用于顯示文檔目錄
let contentHeight = window.innerHeight; //設置目錄高度
let asideContent = '<aside id="sideMenu" style="position: fixed;padding: 80px 15px 20px 15px;top: 0;left: 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:350px;max-width:350px;"><h2>目錄<h2></aside>';
$('.show-content').prepend(asideContent);
$('#sideMenu').append('<ol id="menu_nav_ol" style="list-style:none;margin:0px;padding:0px;">');// 不顯示 li 項前面默認的點標志, 也不使用默認縮進
// 遍歷文章中的所有標題行, 按需添加id值, 并增加記錄到目錄列表中
titles.each(function() {
let tagName = $(this)[0].tagName.toLocaleLowerCase();
let content = $(this).text();
// 若標題的id不存在,則使用新id
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>');
// 綁定目錄li點擊事件,點擊時跳轉(zhuǎn)到對應的位置
$('#menu_nav_ol li').on('click',function() {
let targetId = $(this).attr('class');
$("#"+targetId)[0].scrollIntoView(true);
});
})();
注:以上資料來源于網(wǎng)絡。