Greasy Fork

Greasy Fork is available in English.

专注于ruanyifeng.com博客生成标题导航

针对阮大神的博客没有标题导航制作

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name			专注于ruanyifeng.com博客生成标题导航
// @version			1.0.0
// @description		针对阮大神的博客没有标题导航制作
// @author			@leo
// @match        *://www.ruanyifeng.com/blog/*
// @grant        GM_notification
// @grant        GM_addStyle
// @namespace http://greasyfork.icu/users/810117
// ==/UserScript==

;(() => {
	// 样式注入
	GM_addStyle(`
	.myImportNav {
    position: fixed;
    top: 100px;
    right: 50px;
    width: 300px;
    height: auto;
    display: flex;
    flex-flow: column nowrap;
    align-items: flex-start;
}
.myImportNav .text {
    font-size: 1.5em;
    font-weight: bold;
    margin-bottom: 10px;
}
`)

	window.onload = () => {
		// 查找页面中的所有标题
		const titles = document.querySelectorAll('#alpha-inner article h2')
		console.log(titles)
		// 遍历 titles 为每个 DOM 节点附加一个唯一id,并且将 title 的文字和 唯一id 输出到新数组
		const arr = Array.from(titles).map((item, index) => {
			item.id = `title-${index}`
			return { title: item.innerText, id: item.id }
		})
		console.log(arr)
		// 遍历 arr 在页面中注入悬浮在右上角的导航
		const nav = document.createElement('div')
		nav.className = 'myImportNav'
		arr.forEach((item, index) => {
			const a = document.createElement('a')
			a.className = 'text'
			a.href = `#${item.id}`
			a.innerText = `${index + 1}. ${item.title}`
			nav.appendChild(a)
		})
		document.body.appendChild(nav)
	}
})()