1、安装 Tampermonkey
谷歌浏览器翻墙,从chrome扩展应用商店搜索Tampermonkey
安装好。
点击油猴插件添加新脚本:
然后就可以在编辑器里写脚本为页面添加侧边目录。
2、脚步代码
思路:
查看简书文章页面的源码,可以发现所有的标题行都放在h1,h2,h3,h4,h5,h6 标签内,所以将页面设计成在文章左侧插入列表, 按标题层级进行缩进,点击进行跳转。
将下面的代码贴进编辑器即可。
// ==UserScript==
// @name 简书网站左侧目录生成
// @namespace http://tampermonkey.net/
// @version 1.0.0
// @description 简书网站左侧目录生成,支持非h1标题,支持滚动
// ==/UserScript==
(function () {
'use strict';
initSidebar('.sidebar', '._2rhmJa');
})();
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 = []
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)
}
}
}
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
}
function IdEscape(text) {
return text.replace(/[\s"']/g, '_') //注意这里不加 g 的话就会只匹配第一个匹配,所以会出错
}
function htmlEscape(text) {
return text
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>')
}
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
}
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' })
}
function addAllStyle(highlightColor) {
highlightColor = highlightColor || "#c7254e"
var sheet = newStyleSheet()
function newStyleSheet() {
var style = document.createElement("style");
// 对WebKit hack :(
style.appendChild(document.createTextNode(""));
// 将 <style> 元素加到页面中
document.head.appendChild(style);
return style.sheet;
}
var position = 0
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;
}`)
}
function throttle(fn, interval = 300) {
let canRun = true;
return function () {
if (!canRun) return;
canRun = false;
setTimeout(() => {
fn.apply(this, arguments);
canRun = true;
}, interval);
};
}
网友评论