博客搭建与魔改系列教程导航🚥🚥🚥

阅读约定:每个代码块上方都标了 文件 和 改法(终端命令标 执行位置 和 作用,目录树 / 报错 / 示意内容标 说明)。[Blogroot] 指博客根目录;「新建」是建文件后整段写入,「追加」是放到文件末尾,「替换 / 在 xxx 后插入」是在已有文件里改对应位置。改 themes/ 下的模板和脚本前先备份,主题一升级就会被覆盖。

开始之前:一次装齐依赖

本教程里到处在用的折叠块、提示框,以及后面几节用到的插件,一行装齐:

执行位置:博客根目录终端 | 作用:一次装齐本篇反复用到的插件(折叠块、页脚徽标、磁贴、历史日历、轮播、双栏、wowjs),装完 package.json 的依赖里会多出这些包。

1
2
3
npm install hexo-butterfly-tag-plugins-plus hexo-butterfly-footer-beautify hexo-electric-clock \
hexo-magnet hexo-history-calendar hexo-swiper-bar \
hexo-butterfly-article-double-row hexo-butterfly-wowjs --save
  • hexo-butterfly-tag-plugins-plus:{% folding %}、{% note %} 这些标签由它提供,不装的话整篇文章的折叠块会变成纯文本。
  • 其余插件是按节按需的,只做某一节就只装那一节(每节开头都单独写了命令)。
  • 教程里的 cp 是 Linux / macOS 写法,Windows 用 copy,或者直接资源管理器里复制粘贴——效果一样。
  • 下面所有路径都以 [Blogroot](博客根目录)开头。

炫彩流光文字

炫彩字

新建 [Blogroot]\source\css\brinks.css,写入:

文件:[Blogroot]/source/css/brinks.css | 改法:新建文件,整段写入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.brinks {
display:flex;
z-index:1;
position: relative;
justify-content:center;
font-weight: bold;
background-image: linear-gradient( to left, orangered, orange, gold, lightgreen, cyan, dodgerblue, mediumpurple, hotpink, orangered);
background-size: 100vw 100%;
background-repeat: repeat;
-webkit-background-clip: text;
background-clip: text;
color: transparent;
-webkit-animation: rainbowan 60s linear infinite;
animation: rainbowan 60s linear infinite;
}
@-webkit-keyframes rainbowan {
to { background-position: -2000vw; }
}
@keyframes rainbowan {
to { background-position: -2000vw; }
}

background-size 用 100vw、位移用 -2000vw,两者是整数倍关系(20 个周期),循环时颜色能接上,不会跳。
在 [Blogroot]\_config.butterfly.yml 的 inject.head 添加:

文件:[Blogroot]/_config.butterfly.yml | 改法:在顶层 inject: 下的 head: 列表末尾追加这一条 <link>;缩进保持两格,和其它 - 项对齐。

1
2
3
inject:
head:
- <link rel="stylesheet" href="/css/brinks.css"> #炫彩字

在 [Blogroot]\_config.butterfly.yml 使用:

文件:[Blogroot]/_config.butterfly.yml | 改法:找到顶层 footer:,在它下面加 custom_text:(缩进两格);已有 custom_text 就整行替换。

1
2
footer:
custom_text: <div class="brinks">I wish you to become your own sun, no need to rely on who's light.</div>

全站自定义字体

借鉴:Fomalhaut(猕猴桃)的字体本地化思路;字体本身来自 LXGW WenKai(OFL)。本站改动:按需做字体子集,只保留站内实际用到的字形并转成本地 woff2。

霞鹜文楷

字体是开源免费的(OFL 协议),从 LXGW WenKai 官方仓库取,转成 woff2 再用:

执行位置:本机终端(不必在博客根目录)| 作用:装字体子集工具,把 LXGWWenKai-Regular.ttf 转成 woff2 并输出到 source/font/;--output-file 要写你自己博客的绝对路径。

1
2
3
4
5
6
7
8
9
# 1) 一次性装好字体转换工具
pip install fonttools brotli

# 2) 到 https://github.com/lxgw/LxgwWenKai/releases 下载 LXGWWenKai-Regular.ttf
# (GitHub 慢就用镜像站,或者按发布时间翻一下最新 Release)

# 3) 转 woff2(体积约为 ttf 的 1/3),输出到博客 font 目录
pyftsubset LXGWWenKai-Regular.ttf --flavor=woff2 --layout-features='*' \
--output-file="[Blogroot]\source\font\霞鹜文楷.woff2"

把字体文件放到 [Blogroot]\source\font\霞鹜文楷.woff2 之后,继续往下配。
在 [Blogroot]\source\css\custom.css 末尾添加:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
6
7
@font-face {
font-family: 'myfont';
src: url(/font/霞鹜文楷.woff2) format('woff2');
font-weight: normal;
font-style: normal;
font-display: swap;
}

在 [Blogroot]\_config.butterfly.yml 配置:

文件:[Blogroot]/_config.butterfly.yml | 改法:顶层 font:、blog_title_font:、beautify: 三个键下的对应项按此改写;myfont 必须和上一步 @font-face 里的 font-family 同名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
font:
global_font_size: '16px'
code_font_size: '14px'
font_family: myfont, -apple-system, 'Quicksand', 'PingFang SC', 'Microsoft Yahei', sans-serif;
code_font_family: Consolas, myfont, "Microsoft YaHei", Menlo, monospace

blog_title_font:
font_link:
font_family: myfont, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif

beautify:
enable: true
field: post
title_prefix_icon: '\f863'
title_prefix_icon_color: "#F47466"

在 [Blogroot]\_config.butterfly.yml 的 inject.head 添加:

文件:[Blogroot]/_config.butterfly.yml | 改法:追加到 inject.head 列表末尾;href 里的中文文件名要用 URL 编码(%E9%9C%9E...)才稳。

1
2
3
inject:
head:
- <link rel="preload" as="font" type="font/woff2" href="/font/%E9%9C%9E%E9%B9%9C%E6%96%87%E6%A5%B7.woff2" crossorigin> #正文字体预加载

FontAwesome 图标本地化

图标本地化

不用手动去找 CSS 和字体,装官方 npm 包再拷出来即可:

执行位置:博客根目录终端 | 作用:装 FontAwesome Free 6.5.1,并把 fontawesome.min.css 和三个 woff2 拷进 source/css、source/webfonts。Windows 下 mkdir -p / cp 换成手工建目录、复制粘贴即可。

1
2
3
4
5
6
7
npm install @fortawesome/fontawesome-free@6.5.1 --save-dev

mkdir -p source/css source/webfonts
cp node_modules/@fortawesome/fontawesome-free/css/fontawesome.min.css source/css/
cp node_modules/@fortawesome/fontawesome-free/webfonts/fa-solid-900.woff2 source/webfonts/
cp node_modules/@fortawesome/fontawesome-free/webfonts/fa-regular-400.woff2 source/webfonts/
cp node_modules/@fortawesome/fontawesome-free/webfonts/fa-brands-400.woff2 source/webfonts/

拷完是这样(版本号跟着 npm 包里的一致,6.5.1 就是下面这些文件):

把 Font Awesome Free 6.5.1 的三个字体文件放到 [Blogroot]\source\webfonts\:

说明:示意内容,不需要修改——这是上一步拷完后的文件位置清单,用来核对有没有少拷。

1
2
3
source/webfonts/fa-solid-900.woff2
source/webfonts/fa-regular-400.woff2
source/webfonts/fa-brands-400.woff2

把官方 fontawesome.min.css 放到 [Blogroot]\source\css\fontawesome.min.css,其中三个 @font-face 的 src 改成:

文件:[Blogroot]/source/css/fontawesome.min.css | 改法:这是官方 CSS 里三条 @font-face 的片段,只把三条 src 的 url(...) 换成 /webfonts/... 本地路径,其余规则原样保留。

1
2
3
@font-face{font-family:"Font Awesome 6 Free";font-weight:900;src:url(/webfonts/fa-solid-900.woff2) format("woff2")}
@font-face{font-family:"Font Awesome 6 Free";font-weight:400;src:url(/webfonts/fa-regular-400.woff2) format("woff2")}
@font-face{font-family:"Font Awesome 6 Brands";font-weight:400;src:url(/webfonts/fa-brands-400.woff2) format("woff2")}

在 [Blogroot]\_config.butterfly.yml 配置:

文件:[Blogroot]/_config.butterfly.yml | 改法:顶层 CDN: 下的 option: 里,把 fontawesome: 的值改成 /css/fontawesome.min.css。

1
2
3
CDN:
option:
fontawesome: /css/fontawesome.min.css

在 [Blogroot]\_config.butterfly.yml 的 inject.head 添加:

文件:[Blogroot]/_config.butterfly.yml | 改法:两条一起追加到 inject.head 列表末尾。

1
2
3
4
inject:
head:
- <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
- <link rel="dns-prefetch" href="https://cdn.jsdelivr.net">

菜单图标用 FA6 正式类名:

文件:[Blogroot]/_config.butterfly.yml | 改法:顶层 menu: 列表里按需追加或替换对应项;|| 前后分别是「图标 + 链接」和「悬停图标」,两处图标名要一致。

1
2
menu:
隐私政策||fas fa-shield-halved: /privacy/ || fas fa-shield-halved

一图流背景与遮罩

借鉴:Fomalhaut(猕猴桃)。本站改动:背景图换成本站 WebP,遮罩透明度单独用变量控制。

一图流

把背景图放到 [Blogroot]\source\img\bg.webp。
在 [Blogroot]\_config.butterfly.yml 配置:

文件:[Blogroot]/_config.butterfly.yml | 改法:顶层逐项改值——background 换成你的背景图路径,index_img / default_top_img 留空(一图流不需要单独封面),footer_img: false,mask: 下两个开关按需改。

1
2
3
4
5
6
7
background: /img/bg.webp
index_img:
default_top_img:
footer_img: false
mask:
header: true
footer: true

在 [Blogroot]\source\css\custom.css 末尾添加:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
[data-theme="light"] #footer::before { background: rgba(255,255,255,.5); }
[data-theme="dark"] #footer::before { background: rgba(0,0,0,.5); }
[data-theme="light"] #page-header::before { background: rgba(255,255,255,.3); }
[data-theme="dark"] #page-header::before { background: rgba(0,0,0,.3); }

在 [Blogroot]\_config.butterfly.yml 的 inject.head 添加:

文件:[Blogroot]/_config.butterfly.yml | 改法:追加到 inject.head 列表末尾。

1
2
3
inject:
head:
- <link rel="preload" as="image" href="/img/bg.webp" fetchpriority="high"> #首屏背景预加载

页脚计时器与框架徽标

借鉴:店长(Fomalhaut 整理)。本站改动:插件静态资源改为本地托管,计时起点与徽标列表换成本站配置。

页脚徽标

插件和它要用的静态文件,一条命令装好:

执行位置:博客根目录终端 | 作用:装页脚徽标与计时插件,并把插件自带的 runtime.js、runtime.css、swiperbdage_init.min.js 与 swiper 本体拷进 source/js、source/css。

1
2
3
4
5
6
7
8
9
10
11
npm install hexo-butterfly-footer-beautify hexo-electric-clock --save

mkdir -p source/js source/css
cp node_modules/hexo-butterfly-footer-beautify/lib/runtime.js source/js/
cp node_modules/hexo-butterfly-footer-beautify/lib/runtime.css source/css/
cp node_modules/hexo-butterfly-footer-beautify/lib/swiperbdage_init.min.js source/js/

# 徽标轮播要 swiper,插件本身不带,自己装一份
npm install swiper@8 --save-dev
cp node_modules/swiper/swiper-bundle.min.js source/js/swiper.min.js
cp node_modules/swiper/swiper-bundle.min.css source/css/swiper.min.css

装完这些文件应该在对应路径:

说明:示意内容,不需要修改——核对上面命令拷出来的文件是否都在对应路径。

1
2
3
4
5
source/js/runtime.js
source/css/runtime.css
source/css/swiper.min.css
source/js/swiper.min.js
source/js/swiperbdage_init.min.js

在 [Blogroot]\themes\butterfly\layout\includes\layout.pug 的 footer#footer 内补一层容器:

文件:[Blogroot]/themes/butterfly/layout/includes/layout.pug | 改法:找到 footer#footer(...),确认它下面用 #footer-wrap 包住了 !=partial('includes/footer', ...);Butterfly 5.7.2 已自带这两行,缺了才补(缩进两层)。

1
2
3
footer#footer(style=footer_bg)
#footer-wrap
!=partial('includes/footer', {}, {cache: true})

在 [Blogroot]\source\css\custom.css 末尾添加:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#footer #footer-wrap > * { position: relative; color: var(--light-grey); }
#footer-wrap .footer-other,
#footer-wrap .beian-row,
#footer-wrap #workboard,
#footer-wrap #ghbdages { text-align: center; }
#footer #footer-wrap {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
column-gap: 5px;
}
#footer-wrap > .footer-other { flex: 0 0 100%; order: 0; }
#footer-wrap > #workboard { flex: 0 0 100%; order: 1; }
#footer-wrap > .beian-row,
#footer-wrap > #ghbdages { order: 2; flex: 0 0 auto; max-width: 100%; margin-top: 8px; }
#footer-wrap > #ghbdages {
display: inline-flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
margin: 8px 0 0;
line-height: 1;
}

在 [Blogroot]\_config.butterfly.yml 配置:

文件:[Blogroot]/_config.butterfly.yml | 改法:在文件末尾新增顶层 footer_beautify: 段(插件只认顶层键,别缩进到别的键下面)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
footer_beautify:
enable:
timer: true
bdage: true
priority: 5
enable_page: all
layout:
type: id
name: footer-wrap
index: 0
runtime_js: /js/runtime.js
runtime_css: /css/runtime.css
bdageitem:
- link: https://hexo.io/
shields: https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo
message: 博客框架为Hexo_v8.1.2
- link: https://butterfly.js.org/
shields: https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender
message: 主题版本Butterfly_v5.7.2
- link: https://<你的服务商>/
shields: https://img.shields.io/badge/Host-<你的服务商>-0052D9?style=flat
message: 站点托管信息
- link: http://creativecommons.org/licenses/by-nc-sa/4.0/
shields: https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat
message: 本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可
swiper_css: /css/swiper.min.css
swiper_js: /js/swiper.min.js
swiperbdage_init_js: /js/swiperbdage_init.min.js

小冰分类磁贴

借鉴:小冰(Fomalhaut 整理)。本站改动:分类名称、图标与分栏按本站栏目重排。

分类磁贴

在 [Blogroot]\_config.yml 配置:

文件:[Blogroot]/_config.yml | 改法:在文件末尾新增顶层 magnet: 段;display 里的 name 必须和你的真实分类名完全一致,否则那格是空的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
magnet:
enable: true
priority: 1
enable_page: /
type: categories
devide: 2
display:
- name: 校园生活
display_name: 校园生活
icon: 📚
- name: 编程语言
display_name: 乱写代码
icon: 🎮
- name: music
display_name: 音乐
icon: 🎧
- name: AI
display_name: AI 探索
icon: 👩‍💻
color_setting:
text_color: black
text_hover_color: white
background_color: "#f2f2f2"
background_hover_color: "#b30070"
layout:
type: id
name: recent-posts
index: 0
temple_html: '<div class="recent-post-item" style="width:100%;height: auto"><div id="catalog_magnet">${temple_html_item}</div></div>'
plus_style: ""

装插件:

执行位置:博客根目录终端 | 作用:安装分类磁贴插件。

1
npm install hexo-magnet --save

装完重启 hexo s,磁贴才会被注入。依赖 [Blogroot]\package.json 里的 hexo-magnet。

历史上的今天

借鉴:小冰(Zfour)。本站改动:只保留接入配置,卡片样式与本站侧栏宽度对齐。

历史上的今天

在 [Blogroot]\_config.yml 配置:

文件:[Blogroot]/_config.yml | 改法:在文件末尾新增顶层 history_calendar:、electric_clock: 两段;layout.name 指向侧栏容器 sticky_layout,不要改成 recent-posts。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
history_calendar:
priority: 4
enable: true
enable_page: all
layout:
type: class
name: sticky_layout
index: 0
temple_html: '<div class="card-widget card-history"><div class="card-content"><div class="item-headline"><i class="fas fa-clock fa-spin"></i><span>那年今日</span></div><div id="history-baidu" style="height: 100px;overflow: hidden"><div class="history_swiper-container" id="history-container" style="width: 100%;height: 100%"><div class="swiper-wrapper" id="history_container_wrapper" style="height:20px"></div></div></div></div></div>'

electric_clock:
priority: 5
enable: false
enable_page: all
layout:
type: class
name: sticky_layout
index: 0

装插件:

执行位置:博客根目录终端 | 作用:安装历史日历与电子钟插件(电子钟默认 enable: false,想用再开)。

1
npm install hexo-history-calendar hexo-electric-clock --save

「历史上的今天」的模板里用到了 swiper 容器,所以要在「页脚计时器与框架徽标」那节把 swiper.min.js / swiper.min.css 也放到 source/js、source/css 下(那一节有完整命令)。
依赖 [Blogroot]\package.json 里的 hexo-history-calendar、hexo-electric-clock。

首页置顶轮播与文章双栏

借鉴:店长 / 小冰(Fomalhaut 整理)。本站改动:轮播与双栏配置按本站首页结构重排,静态资源改为本地加载。

轮播与双栏

在 [Blogroot]\_config.yml 配置:

文件:[Blogroot]/_config.yml | 改法:在文件末尾新增顶层 swiper:、butterfly_article_double_row: 两段;stylus: 是主题自带的压缩开关,已有就只核对值,别重复写。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
swiper:
enable: true
priority: 2
enable_page: /
layout:
type: id
name: recent-posts
index: 0
temple_html: '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container">${temple_html_item}</div></div>'
plus_style: ""

butterfly_article_double_row:
enable: true

stylus:
compress: true

这一步要两个插件:

执行位置:博客根目录终端 | 作用:安装置顶轮播与首页双栏插件;swiper 本体复用上一节拷进 source/js、source/css 的本地文件。

1
2
3
npm install hexo-swiper-bar hexo-butterfly-article-double-row --save
# 轮播依赖 swiper 本体,同样复用「页脚计时器与框架徽标」那节拷过来的
# source/js/swiper.min.js 与 source/css/swiper.min.css

在文章 front matter 里写 top: 1。
在 [Blogroot]\source\css\custom.css 末尾添加 5.x 双排适配:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾(末尾那段 .low-perf 降级规则一并加上)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@media screen and (min-width: 769px) {
#recent-posts > .recent-post-items {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-content: flex-start;
width: 100%;
}
#recent-posts > .recent-post-items > .recent-post-item {
display: flex;
flex-direction: column;
width: 49%;
height: auto !important;
margin-top: 1rem;
}
#recent-posts > .recent-post-items > .recent-post-item > .post_cover {
order: 0 !important;
width: 100% !important;
height: 200px;
flex: 0 0 200px;
}
#recent-posts > .recent-post-items > .recent-post-item > .recent-post-info {
width: 100% !important;
padding: 0 40px;
margin-top: 1em;
}
#recent-posts > .recent-post-items > .recent-post-item > .recent-post-info > .content {
display: none;
}
#recent-posts > .recent-post-items > .recent-post-item > .recent-post-info > .article-title {
-webkit-line-clamp: 1;
margin-top: .3rem;
margin-bottom: .3rem;
font-size: 1.2em;
line-height: 1.4;
color: var(--text-highlight-color);
}
#recent-posts > .recent-post-items > .recent-post-item > .recent-post-info > .article-meta-wrap {
margin-bottom: 1rem;
}
#recent-posts > .recent-post-items > .pagination,
#recent-posts > .recent-post-items > #pagination,
#recent-posts > .recent-post-items > nav {
width: 100%;
flex: 0 0 100%;
}
}
html.low-perf #recent-posts > .recent-post-items > .recent-post-item {
content-visibility: auto;
contain-intrinsic-size: auto 320px;
}

页脚备案三连(ICP / 公安 / 萌ICP)

备案三连

在 [Blogroot]\_config.butterfly.yml 新增顶层 beian 段:

文件:[Blogroot]/_config.butterfly.yml | 改法:新增顶层 beian: 段(放文件末尾即可);三个编号换成你自己的,还没下号就保持 pending: true。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
beian:
icp:
number: ICP备<你的备案号>号-1
label: ICP备
link: https://beian.miit.gov.cn/
pending: true
police:
number: 公网安备<你的备案号>号
label: 公网安备
code: ''
icon: /img/beian.png
link: 'https://beian.mps.gov.cn/#/query/webSearch'
pending: true
moe:
number: 萌ICP备<你的编号>号
label: 萌ICP备
link: https://icp.gov.moe/
pending: false

在 [Blogroot]\themes\butterfly\layout\includes\footer.pug 末尾添加:

文件:[Blogroot]/themes/butterfly/layout/includes/footer.pug | 改法:追加到文件末尾,缩进为 0(和已有的 if theme.footer.custom_text 同级)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//- 备案信息三连
if theme.beian
.beian-row
- const icp = theme.beian.icp
if icp
if icp.pending
span.beian-item.beian-item--pending(title='工信部 ICP 备案办理中,下号后显示备案号')
span.beian-item__key= icp.label || 'ICP备'
span.beian-item__val 办理中
else
a.beian-item.beian-item--icp(href=icp.link target='_blank' rel='noopener noreferrer' title=icp.number)
span.beian-item__key= icp.label || 'ICP备'
span.beian-item__val= icp.number.replace(icp.label || '', '')
- const police = theme.beian.police
if police
if police.pending
span.beian-item.beian-item--pending(title='公安联网备案办理中,下号后显示备案号')
span.beian-item__key= police.label || '公网安备'
span.beian-item__val 办理中
else
a.beian-item.beian-item--icp(href=`${police.link}?code=${police.code}` target='_blank' rel='noopener noreferrer' title=police.number)
if police.icon
img.beian-police-icon(src=url_for(police.icon) alt='公安备案')
span.beian-item__key= police.label || '公网安备'
span.beian-item__val= police.number.replace(police.label || '', '')
- const moe = theme.beian.moe
if moe
a.beian-item.beian-item--moe(href=moe.link target='_blank' rel='noopener noreferrer' title='萌国 ICP 备案(非官方趣味标识,非工信部备案)')
span.beian-item__key= moe.label || '萌ICP备'
span.beian-item__val= moe.number.replace(moe.label || '', '')

在 [Blogroot]\source\css\custom.css 末尾添加:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#footer-wrap .beian-row {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
gap: 5px;
margin-top: 8px;
}
.beian-item {
display: inline-flex;
align-items: stretch;
overflow: hidden;
height: 20px;
border-radius: 3px;
font-size: 11px;
line-height: 20px;
white-space: nowrap;
text-decoration: none !important;
transition: transform .25s ease, box-shadow .25s ease;
}
.beian-item__key,
.beian-item__val { display: inline-flex; align-items: center; color: #fff; }
.beian-item__key { padding: 0 5px; background: #5a6b7b; }
.beian-item__val { padding: 0 6px; background: #5ea6e5; }
.beian-item--pending { cursor: default; }
.beian-item--pending .beian-item__key { background: #6b7684; }
.beian-item--pending .beian-item__val { background: #9aa7b4; }
.beian-item--moe .beian-item__key { background: #7a3a63; }
.beian-item--moe .beian-item__val { background: #f838b2; }
a.beian-item:hover { transform: translateY(-2px); box-shadow: 0 3px 10px rgba(0,0,0,.18); }
.beian-police-icon { width: 12px; height: 12px; object-fit: contain; margin-right: 4px; }
[data-theme="dark"] .beian-item--pending .beian-item__val { background: #6f7b88; }
@media screen and (max-width: 768px) {
#footer-wrap .beian-row { gap: 4px; }
.beian-item { font-size: 10px; height: 18px; line-height: 18px; }
}

pending: true 显示「办理中」不生成链接;下号后填 number / code 并把 pending 改成 false。

昼夜更替(山河日月版)

借鉴:店长(Fomalhaut 整理)。本站改动:过场脚本重写为自包含实现,动画时长与降级策略按本站性能模式调整。

黄昏落幕过场

效果:点右上角的月亮/太阳,整屏不是直接换色,而是走一段「黄昏落幕」——太阳从左上方往右下沉、月亮从左下方往右上爬,星星一颗颗亮起来,远山剪影与地平线余光跟着压暗;切回白天时完全反向(月亮落、太阳升、星星退场)。最后 350ms 从点击处做一个圆形揭幕,把新主题「揭」出来。

核心是一个自包含脚本:DOM、渐变、关键帧全部由 JS 现场创建,不依赖任何外部 CSS,所以换主题皮肤也不会互相打架。

新建 [Blogroot]\source\js\fomal\night.js,写入:

文件:[Blogroot]/source/js/fomal/night.js | 改法:新建文件,整段写入;本站 source/js/fomal/night.js 已经是这份实现,改动时对照补齐即可,不要另建第二份。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*!
* 昼夜切换 2.0「黄昏落幕」——自包含实现(不依赖任何外部 CSS)
* 日月沿同一条圆弧升/降,落点为画面正上方同一位置;共 1500ms,末段从点击处圆形揭幕。
* 档位 localStorage.darkTransition:off / light / standard / flourish(默认 standard)
* 减弱动态效果(prefers-reduced-motion: reduce)保留过场但压到约 45% 时长。
*/
(function () {
'use strict'

var TOTAL = 1500
var REVEAL_AT = 1150
var REVEAL = 350
var running = false
var overlay = null
var revealTimer = 0
var finishTimer = 0
var cleanupTimer = 0
var overlayGuard = 0
var revealRAF = 0
var runGen = 0
var pending = false

function root () { return document.documentElement }
function isDark () { return root().getAttribute('data-theme') === 'dark' }
function reduced () {
try { return window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches } catch (e) { return false }
}
function tier () {
var t = 'standard'
try { t = window.localStorage.getItem('darkTransition') || 'standard' } catch (e) {}
return ['off', 'light', 'standard', 'flourish'].indexOf(t) >= 0 ? t : 'standard'
}

function applyTheme (toDark) {
var btf = window.btf || {}
var mode = toDark ? 'dark' : 'light'
var activate = toDark ? (btf.activateDarkMode || window.activateDarkMode)
: (btf.activateLightMode || window.activateLightMode)
if (typeof activate === 'function') {
try { activate() } catch (e) { root().setAttribute('data-theme', mode) }
} else {
root().setAttribute('data-theme', mode)
}
var save = btf.saveToLocal || window.saveToLocal
if (save && typeof save.set === 'function') {
try { save.set('theme', mode, 2) } catch (e) {}
} else {
try { localStorage.setItem('theme', JSON.stringify({ value: mode, expiry: Date.now() + 2 * 86400000 })) } catch (e) {}
}
try {
document.body.classList.toggle('DarkMode', !!toDark)
localStorage.setItem('isDark', toDark ? 'true' : 'false')
if (window.globalFn && typeof window.globalFn.themeChange === 'function') window.globalFn.themeChange()
} catch (e) {}
var icons = document.querySelectorAll('#modeicon, use#modeicon')
for (var i = 0; i < icons.length; i++) {
try { icons[i].setAttribute('xlink:href', toDark ? '#icon-sun' : '#icon-moon') } catch (e) {}
try { icons[i].setAttribute('href', toDark ? '#icon-sun' : '#icon-moon') } catch (e) {}
}
}

function el (css, parent) {
var d = document.createElement('div')
d.setAttribute('style', css)
if (parent) parent.appendChild(d)
return d
}

function anim (node, frames, opts) {
try {
if (node && node.animate) return node.animate(frames, opts)
} catch (e) {}
return null
}

function cleanup () {
var hadPending = pending
pending = false
window.clearTimeout(revealTimer)
window.clearTimeout(finishTimer)
window.clearTimeout(cleanupTimer)
window.clearTimeout(overlayGuard)
if (revealRAF) { try { cancelAnimationFrame(revealRAF) } catch (e) {} revealRAF = 0 }
if (overlay && overlay.parentNode) overlay.parentNode.removeChild(overlay)
overlay = null
running = false
if (hadPending) {
window.setTimeout(function () { pending = false; run() }, 40)
}
}

// 结束揭幕:无论 rAF 是否被节流(切标签页/后台),都由这里兜底收尾
function finishReveal (gen) {
if (gen !== undefined && gen !== runGen) return
if (!overlay) return
var mask = 'radial-gradient(circle 160vmax at 50% 50%, transparent 99%, #000 100%)'
overlay.style.webkitMaskImage = mask
overlay.style.maskImage = mask
overlay.style.visibility = 'hidden'
running = false
window.clearTimeout(revealTimer)
window.clearTimeout(finishTimer)
var g = runGen
cleanupTimer = window.setTimeout(function () { if (g === runGen) cleanup() }, 80)
}

function run () {
if (running) {
// 动画进行中再点:记一个待办,等这一轮收尾后立刻补一次,避免“点了没反应”
if (overlay) { pending = true; return }
running = false
}
running = true
// 任何异常(浏览器兼容/第三方脚本干扰)都不能把 running 卡死,否则之后所有点击都“没反应”
try { startRun() } catch (e) { cleanup() }
}

function startRun () {
var my = ++runGen
var toDark = !isDark()
var t = tier()

cleanup()
running = true

if (t === 'off') { applyTheme(toDark); running = false; return }

var pt = window.__dmPoint || { x: Math.round(window.innerWidth / 2), y: Math.round(window.innerHeight * 0.42) }
var k = (reduced() ? 0.45 : 1) * (t === 'light' ? 0.75 : 1)
var total = TOTAL * k
var revealAt = REVEAL_AT * k
var reveal = REVEAL * k
var starCount = (t === 'flourish' ? 44 : t === 'standard' ? 30 : 14)
if (window.innerWidth <= 600) starCount = Math.round(starCount / 2)
var flourish = t === 'flourish'

// 全屏幕布(不透明底,避免网页内容透出)
overlay = el('position:fixed;inset:0;z-index:88888890;overflow:hidden;pointer-events:none;background:#241f45;', null)
document.body.appendChild(overlay)

// ① 黄昏底色
var dawn = el('position:absolute;inset:0;background:'
+ 'linear-gradient(to top,#ffb26b 0%,#ef7d67 20%,#c06a83 42%,#7b5480 62%,#4b3a72 82%,#2b2450 100%);', overlay)

// ② 夜空层
var night = el('position:absolute;inset:0;background:'
+ 'linear-gradient(to top,#070d26 0%,#101a3e 30%,#1d2a52 58%,#2f2c58 80%,#3b3163 100%);', overlay)

// ③ 地平线余光
var horizon = el('position:absolute;left:0;right:0;bottom:0;height:56%;opacity:0;background:radial-gradient(75% 100% at 50% 100%, rgba(255,196,120,.85) 0%, rgba(244,132,120,.55) 30%, rgba(120,70,140,.25) 58%, rgba(20,20,50,0) 82%);', overlay)

// ④ 星星
var stars = el('position:absolute;inset:0;', overlay)
for (var i = 0; i < starCount; i++) {
var sx = (Math.random() * 100).toFixed(2) + '%'
var sy = (Math.random() * 66).toFixed(2) + '%'
var ss = (1 + Math.random() * 1.8).toFixed(2) + 'px'
el('position:absolute;left:' + sx + ';top:' + sy + ';width:' + ss + ';height:' + ss + ';border-radius:50%;background:#fff;opacity:0;'
+ 'box-shadow:0 0 6px rgba(255,255,255,.8),0 0 14px rgba(160,200,255,.35);', stars)
}

// ⑤ 太阳 / 月亮:容器放在左上角,用 translate 走弧形轨迹(统一从左往右)
var W = window.innerWidth
var H = window.innerHeight
var D = function (x, y) { return 'translate(' + Math.round(x * W) + 'px,' + Math.round(y * H) + 'px)' }

// 落下:左上 → 右下(从左往右,逐渐沉入地平线)
var SET_PATH = [D(0.24, 0.26), D(0.44, 0.32), D(0.68, 0.56), D(0.88, 0.84)]
// 升起:左下 → 右上(从左往右,逐渐升到天空)
var RISE_PATH = [D(0.10, 0.86), D(0.28, 0.68), D(0.54, 0.44), D(0.76, 0.28)]

function celestial (size, style, haloSize, haloStyle) {
var wrap = el('position:absolute;left:0;top:0;width:0;height:0;will-change:transform;', overlay)
var halo = el('position:absolute;left:' + (-haloSize / 2) + 'px;top:' + (-haloSize / 2) + 'px;width:' + haloSize + 'px;height:' + haloSize + 'px;border-radius:50%;opacity:0;' + haloStyle, wrap)
var disc = el('position:absolute;left:' + (-size / 2) + 'px;top:' + (-size / 2) + 'px;width:' + size + 'px;height:' + size + 'px;border-radius:50%;' + style, wrap)
return { wrap: wrap, halo: halo, disc: disc }
}

var sunSet = celestial(92,
'background:radial-gradient(circle at 38% 34%,#fff8d6 0 14%,#ffe483 42%,#ffb43d 74%,#f0851a 100%);'
+ 'box-shadow:0 0 46px 14px rgba(255,190,90,.5),0 0 120px 40px rgba(255,150,60,.18);',
360,
'background:radial-gradient(circle,rgba(255,205,120,.55) 0%,rgba(255,170,90,.22) 42%,rgba(255,150,60,0) 72%);')

var moonSet = celestial(84,
'background:radial-gradient(circle at 34% 30%,#fff 0 34%,#e8eefc 64%,#c2ccdf 100%);'
+ 'box-shadow:0 0 34px 10px rgba(190,210,255,.3),inset -6px -8px 18px rgba(120,140,190,.35);',
240,
'background:radial-gradient(circle,rgba(200,220,255,.35) 0%,rgba(160,190,255,.12) 45%,rgba(120,150,255,0) 72%);')

var sun = sunSet.disc
var sunHalo = sunSet.halo
var sunWrap = sunSet.wrap
var moon = moonSet.disc
var moonHalo = moonSet.halo
var moonWrap = moonSet.wrap

// ⑥ 远山剪影
el('position:absolute;left:0;right:0;bottom:0;height:32%;opacity:.94;background-repeat:no-repeat;background-position:bottom center;background-size:100% 100%;'
+ 'background-image:url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 1440 200\' preserveAspectRatio=\'none\'><path fill=\'%230b1022\' d=\'M0 200V152l126-24 132 30 138-44 148 36 140-30 152 34 158-26 150 32 152-20 144 24V200Z\'/><path fill=\'%23222a4e\' d=\'M0 200V116l150-34 132 44 156-62 138 48 152-66 152 56 160-38 142 46 158-28 100 22V200Z\'/></svg>");', overlay)

var ease = 'cubic-bezier(.42,.05,.28,1)'

// 先落一帧再切主题
void overlay.offsetWidth
requestAnimationFrame(function () {
requestAnimationFrame(function () { play() })
})

function play () {
if (!overlay) return
applyTheme(toDark)

var starEls = stars.children
var pathFrames = function (path) {
return [
{ transform: path[0], offset: 0 },
{ transform: path[1], offset: 0.36 },
{ transform: path[2], offset: 0.70 },
{ transform: path[3], offset: 1 }
]
}
var travel = function (node, path, dur, delay) {
return anim(node, pathFrames(path), { duration: dur, delay: delay || 0, easing: 'linear', fill: 'forwards' })
}

if (toDark) {
// 入夜:太阳从左往右落下;月亮从左往右升起
dawn.style.opacity = '1'
night.style.opacity = '0'
horizon.style.opacity = '0'
sun.style.opacity = '1'
sunHalo.style.opacity = '1'
sunWrap.style.transform = SET_PATH[0]
moonWrap.style.transform = RISE_PATH[0]

travel(sunWrap, SET_PATH, 640 * k, 0)
travel(moonWrap, RISE_PATH, 560 * k, 620 * k)
anim(sun, [{ opacity: 1 }, { opacity: 1, offset: .5 }, { opacity: 0 }],
{ duration: 660 * k, easing: 'ease-in', fill: 'forwards' })
anim(sunHalo, [{ opacity: 1 }, { opacity: .9, offset: .4 }, { opacity: 0 }],
{ duration: 660 * k, easing: 'ease-in', fill: 'forwards' })
anim(moon, [{ opacity: 0 }, { opacity: 1 }],
{ duration: 220 * k, delay: 640 * k, easing: 'ease-out', fill: 'forwards' })
anim(moonHalo, [{ opacity: 0 }, { opacity: 1 }],
{ duration: 260 * k, delay: 640 * k, easing: 'ease-out', fill: 'forwards' })
anim(night, [{ opacity: 0 }, { opacity: 1 }], { duration: 1200 * k, easing: 'ease-in', fill: 'forwards' })
anim(dawn, [{ opacity: 1 }, { opacity: .9, offset: .38 }, { opacity: 0 }], { duration: 1200 * k, easing: 'ease-in', fill: 'forwards' })
anim(horizon, [{ opacity: 0 }, { opacity: 1, offset: .35 }, { opacity: 0 }], { duration: 1100 * k, easing: 'ease-out', fill: 'forwards' })
for (var s2 = 0; s2 < starEls.length; s2++) {
anim(starEls[s2], [{ opacity: 0, transform: 'scale(.6)' }, { opacity: 0.5 + Math.random() * 0.5, transform: 'scale(1)' }],
{ duration: 760 * k, delay: (360 + s2 * 11) * k, easing: 'ease-out', fill: 'forwards' })
}
} else {
// 破晓:月亮从左往右落下;太阳从左往右升起
dawn.style.opacity = '0'
night.style.opacity = '1'
horizon.style.opacity = '0'
sunWrap.style.transform = RISE_PATH[0]
moonWrap.style.transform = SET_PATH[0]
sun.style.opacity = '0'
sunHalo.style.opacity = '0'
moon.style.opacity = '1'
moonHalo.style.opacity = '1'

travel(moonWrap, SET_PATH, 640 * k, 0)
travel(sunWrap, RISE_PATH, 560 * k, 620 * k)
anim(moon, [{ opacity: 1 }, { opacity: 1, offset: .5 }, { opacity: 0 }],
{ duration: 660 * k, easing: 'ease-in', fill: 'forwards' })
anim(moonHalo, [{ opacity: 1 }, { opacity: .9, offset: .4 }, { opacity: 0 }],
{ duration: 660 * k, easing: 'ease-in', fill: 'forwards' })
anim(sun, [{ opacity: 0 }, { opacity: 1 }],
{ duration: 220 * k, delay: 640 * k, easing: 'ease-out', fill: 'forwards' })
anim(sunHalo, [{ opacity: 0 }, { opacity: .95 }],
{ duration: 260 * k, delay: 640 * k, easing: 'ease-out', fill: 'forwards' })
anim(horizon, [{ opacity: 0 }, { opacity: .95, offset: .45 }, { opacity: .55 }],
{ duration: 1200 * k, easing: 'ease-out', fill: 'forwards' })
anim(dawn, [{ opacity: 0 }, { opacity: 1 }], { duration: 1100 * k, delay: 200 * k, easing: 'ease-out', fill: 'forwards' })
anim(night, [{ opacity: 1 }, { opacity: 0 }], { duration: 1150 * k, easing: 'ease-in-out', fill: 'forwards' })
for (var q = 0; q < starEls.length; q++) {
starEls[q].style.opacity = '0.85'
anim(starEls[q], [{ opacity: 0.85 }, { opacity: 0 }], { duration: 520 * k, delay: q * 6 * k, easing: 'ease-in', fill: 'forwards' })
}
}

if (flourish) {
var meteor = el('position:absolute;left:0;top:0;width:2px;height:2px;border-radius:50%;background:#fff;opacity:0;box-shadow:0 0 10px 2px rgba(255,255,255,.7);', overlay)
anim(meteor, [
{ opacity: 0, transform: 'translate(18vw,6vh)' },
{ opacity: 1, offset: .25 },
{ opacity: 0, transform: 'translate(56vw,34vh)' }
], { duration: 700 * k, delay: 620 * k, easing: 'ease-out', fill: 'forwards' })
}
}

// 揭幕:从点击点向外扩张的圆形遮罩
revealTimer = window.setTimeout(function () {
if (my !== runGen || !overlay) return
if (document.hidden) { finishReveal(); return }
var x = pt.x, y = pt.y
var maxR = Math.round(Math.sqrt(window.innerWidth * window.innerWidth + window.innerHeight * window.innerHeight))
var start = 0
function frame (now) {
if (my !== runGen || !overlay) return
if (!start) start = now
var p = Math.min(1, (now - start) / Math.max(1, reveal))
var e = 1 - Math.pow(1 - p, 3)
var r = Math.round(e * maxR)
var mask = 'radial-gradient(circle ' + r + 'px at ' + x + 'px ' + y + 'px, transparent 97%, #000 100%)'
overlay.style.webkitMaskImage = mask
overlay.style.maskImage = mask
if (p < 1) revealRAF = requestAnimationFrame(frame)
else finishReveal(my)
}
revealRAF = requestAnimationFrame(frame)
}, Math.round(revealAt))

// 兜底:rAF 被节流(切标签页/后台/低电量)时也要收尾,避免遮罩停在半路
finishTimer = window.setTimeout(function () { finishReveal(my) }, Math.round(revealAt + reveal + 260))
// 最外层保险(必须可被 cleanup 取消,否则上一轮的定时器会掐断下一轮动画)
overlayGuard = window.setTimeout(function () { if (my === runGen && overlay) finishReveal(my) }, Math.round(total) + 1200)
}

function bind () {
var nodes = document.querySelectorAll('#nightmode-button, .sun_moon, .icon-V')
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i]
if (n.getAttribute('data-dm-bound') === '1') continue
if (n.hasAttribute('onclick') && n.parentNode) {
// 克隆替换:把主题写死的内联 onclick 彻底丢掉,杜绝双触发
var c = n.cloneNode(true)
c.removeAttribute('onclick')
n.parentNode.replaceChild(c, n)
n = c
}
n.setAttribute('data-dm-bound', '1')
n.addEventListener('click', function (e) {
e.preventDefault()
e.stopPropagation()
e.stopImmediatePropagation()
run()
return false
}, true)
}
}

document.addEventListener('pointerdown', function (e) {
window.__dmPoint = { x: Math.round(e.clientX), y: Math.round(e.clientY) }
}, true)

document.addEventListener('visibilitychange', function () {
if (document.hidden && overlay) finishReveal(runGen)
})
window.addEventListener('pagehide', cleanup)
document.addEventListener('pjax:complete', function () { cleanup(); bind() })
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', bind)
else bind()

// 占住全局函数:主题的 sun_moon.js(async 加载)会重新声明 switchNightMode,
// 用访问器把赋值吞掉,保证任何调用(导航按钮/右键菜单/侧边栏/美化面板)都走这里
try {
Object.defineProperty(window, 'switchNightMode', {
configurable: true,
get: function () { return run },
set: function () {}
})
} catch (e) {
window.switchNightMode = run
}
window.setTimeout(function () { try { if (window.switchNightMode !== run) window.switchNightMode = run } catch (e) {} }, 400)
window.setTimeout(function () { try { if (window.switchNightMode !== run) window.switchNightMode = run } catch (e) {} }, 1500)
})()

[Blogroot]\_config.butterfly.yml 的 inject.bottom 加一行:

文件:[Blogroot]/_config.butterfly.yml | 改法:追加到 inject.bottom 列表末尾;defer 要保留,提前执行会拿不到 DOM。

1
2
3
inject:
bottom:
- <script defer src="/js/fomal/night.js?v=1"></script> #昼夜切换 2.0

按钮用主题自带的那个就行([Blogroot]\themes\butterfly\layout\includes\header\nav.pug):

说明:主题自带按钮的片段,一般不需要修改——要是昼夜切换按钮丢了,就照这段在 themes/butterfly/layout/includes/header/nav.pug(第 34 行附近)恢复。

1
2
3
a.sun_moon.faa-parent.animated-hover(onclick='switchNightMode()', title=_p('rightside.night_mode_title') id="nightmode-button")
svg.faa-tada(style="height:25px;width:25px;fill:currentColor;position:relative;top:7px", viewBox='0 0 1024 1024')
use#modeicon(xlink:href='#icon-moon')

三个坑,踩过就记住:

  • 主题自带的 sun_moon.js 会定义同名的全局 switchNightMode,两份一起跑就是「动画播一半被另一份掐断」。脚本里用 Object.defineProperty(window, 'switchNightMode', ...) 占住这个全局名,并且加载后 400ms / 1500ms 再赋一次值,防止被异步脚本后覆盖。
  • 连点:动画中再点不再被静默丢弃,记一个 pending,本轮收尾后自动补播一次;每次运行带 runGen 代次,旧一轮的定时器 / rAF 一律作废,不会出现「上一轮把这一轮掐了」。
  • 遮罩闪烁:mask 从 circle 0 直接跳到 160vmax 再叠一层 opacity:0,第一帧会整块消失。改成 requestAnimationFrame 逐帧写半径,overlay 全程 opacity:1,结束后才 visibility:hidden。

档位(localStorage.darkTransition):off 直接切换/light 800ms 简化/standard 1500ms 默认/flourish 多一颗流星。系统开了「减少动态效果」时保留过场但压到 45% 时长,不做成直接消失。

切换样式:山河日月 / 图形(旧版)

上面那套「黄昏落幕」是后来写的版本,但不少人(包括我自己)还是惦记主题原配那套:整屏青绿→橙黄的渐变圆盘转一圈、日月在同一点叠着做透明度互换。与其二选一删掉一个,不如做成开关。

键:localStorage.hgNightStyle,scene(默认,山河日月)/ cuteen(图形,旧版转盘)。

分工:新版的 DOM、渐变、关键帧全在 night.js 里自建;旧版反过来——只负责插 DOM,动画交给主题自带的 themes/butterfly/source/css/_layout/sun_moon.styl(.Cuteen_DarkSky / .Cuteen_DarkPlanet / #sun / #moon),这些样式本来就编译进主题 CSS,不用补。

1. night.js:读样式 + 分流

文件:[Blogroot]/source/js/fomal/night.js | 改法:三处追加,不要新建第二个文件。

(a) 状态区(var pending = false 后面)加:

1
2
3
4
5
6
7
8
var STYLE_KEY = 'hgNightStyle'

// 过场样式:scene=山河日月(默认) / cuteen=图形(旧版转盘)
function style () {
var v = 'scene'
try { v = window.localStorage.getItem(STYLE_KEY) || 'scene' } catch (e) {}
return v === 'cuteen' ? 'cuteen' : 'scene'
}

(b) startRun() 里,紧跟「关档直接切主题」那行之后:

1
2
3
4
if (t === 'off') { applyTheme(toDark); running = false; return }

// 图形(旧版 Cuteen 转盘):插入旧版 DOM,走主题自带的 Cuteen 动画
if (style() === 'cuteen') { runCuteen(my, toDark, t); return }

(c) 在 bind() 之前插入旧版播放器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* 图形切换(旧版):插入 .Cuteen_DarkSky / .Cuteen_DarkPlanet,
* 转盘动画与日月由主题的 _layout/sun_moon.styl 提供;
* 500ms 时日月透明度互换,1000ms 后整块淡出移除。
*/
function runCuteen (my, toDark, t) {
var k = (reduced() ? 0.45 : 1) * (t === 'light' ? 0.75 : 1)

var sky = document.createElement('div')
sky.className = 'Cuteen_DarkSky'
var planet = document.createElement('div')
planet.className = 'Cuteen_DarkPlanet'
// 转盘一圈时长由自定义属性驱动(custom.css 里 !important 的动画也会读它)
sky.style.setProperty('--hg-cut-dur', (1000 * k) + 'ms')
var sun = document.createElement('div')
sun.id = 'sun'
sun.style.transition = 'opacity .45s ease'
sun.style.opacity = toDark ? '1' : '0'
var moon = document.createElement('div')
moon.id = 'moon'
moon.style.transition = 'opacity .45s ease'
moon.style.opacity = toDark ? '0' : '1'
planet.appendChild(sun)
planet.appendChild(moon)
sky.appendChild(planet)
document.body.appendChild(sky)
overlay = sky

// 先落一帧,让 :before 的 2s 过渡从「浅色」起步
void sky.offsetWidth
applyTheme(toDark)
nightToast(toDark)

// 500ms:日月互换(复用 cleanup 会清的定时器槽位)
revealTimer = window.setTimeout(function () {
if (my !== runGen) return
sun.style.opacity = toDark ? '0' : '1'
moon.style.opacity = toDark ? '1' : '0'
}, Math.round(500 * k))

// 半圈后:整块淡出
finishTimer = window.setTimeout(function () {
if (my !== runGen) return
sky.style.transition = 'opacity .5s ease'
sky.style.opacity = '0'
}, Math.round(1000 * k))

// 收尾移除
cleanupTimer = window.setTimeout(function () {
if (my !== runGen) return
cleanup()
}, Math.round(1000 * k) + 620)

// 保险:动画被节流/中间出错时也要复位
overlayGuard = window.setTimeout(function () {
if (my === runGen && overlay) cleanup()
}, Math.round(1000 * k) + 2200)
}

2. 转盘时长必须走 CSS 变量(本节最坑的一处)

旧版动画在 custom.css 里带了 !important,你就算在 JS 里写 planet.style.animationDuration = '3s' 也完全无效(内联样式优先级低于 !important)。唯一能干过它的是自定义属性:把时长替换成 var(--hg-cut-dur, 1s),再由 JS 写到 .Cuteen_DarkSky 上,让子元素继承。

文件:[Blogroot]/source/css/custom.css | 改法:把旧版那段的动画声明替换掉:

1
2
3
4
.Cuteen_DarkPlanet {
-webkit-animation: CuteenPlanetMove var(--hg-cut-dur, 1s) cubic-bezier(0.7, 0, 0, 1) !important;
animation: CuteenPlanetMove var(--hg-cut-dur, 1s) cubic-bezier(0.7, 0, 0, 1) !important;
}

(.Cuteen_DarkSky{transition:opacity .75s}、#sun/#moon{transition:opacity .4s} 这些保持原样即可。)

3. 面板里加一行开关

文件:[Blogroot]/source/js/fomal/panel.js | 改法:函数区、HTML 片段、导出与 syncAll() 各加一处。

函数(放在 setTier 之前):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* ── 昼夜切换样式:山河日月 / 图形(旧版 Cuteen 转盘) ────────────────── */
function nightStyle () { return sget(K.nightStyle, 'scene') === 'cuteen' ? 'cuteen' : 'scene' }
function syncNightStyle () {
var current = nightStyle()
var buttons = d.querySelectorAll('.settings .dm-seg button[data-ns]')
for (var i = 0; i < buttons.length; i++) {
buttons[i].classList.toggle('is-on', buttons[i].getAttribute('data-ns') === current)
}
var note = $('nightStyleNote')
if (note) {
note.textContent = current === 'cuteen'
? '图形:旧版圆盘转动 + 日月互换'
: '山河日月:太阳沉落 / 月亮升起 + 星星'
}
}

function setNightStyle (value) {
if (['scene', 'cuteen'].indexOf(value) < 0) return
sset(K.nightStyle, value)
syncNightStyle()
toast('切换样式:' + (value === 'cuteen' ? '图形(旧版)' : '山河日月'), 'info')
}

HTML:接在「昼夜切换」那行 </div></div> 之后、互动挂件 标题之前:

1
2
3
4
5
6
'<div class="feature-opt dm-wide"><span>切换样式<small id="nightStyleNote">点击日月的过场效果</small></span>' +
'<div class="dm-seg" role="group" aria-label="昼夜切换样式">' +
'<button type="button" data-ns="scene" onclick="hgSetNightStyle(\'scene\')">山河日月</button>' +
'<button type="button" data-ns="cuteen" onclick="hgSetNightStyle(\'cuteen\')">图形(旧版)</button>' +
'</div>' +
'</div>' +

导出(跟 w.hgSetTier = setTier 放一起):

1
w.hgSetNightStyle = setNightStyle

syncAll() 末尾补一行 syncNightStyle()(和 syncTier() 并列),否则重开面板时按钮状态是旧的。

如果面板脚本是从 boot.js 的 KEYS 里取键名,记得补 nightStyle: 'hgNightStyle',;没有 boot.js 就在 panel.js 里直接用字符串 'hgNightStyle' 当键,两处必须一致。

4. 验证

点右上角日月两次,各看一遍:

  • 面板选「图形(旧版)」:能截到的中间画面是整屏 青绿→橙黄 渐变盘 + 左侧大太阳;入夜则变成 紫→青 的深色渐变淡入,1000ms 后整块消失。
  • 面板选「山河日月」:回到太阳沉落、月亮升起、星星渐显,末尾圆形揭幕。

Console 里 localStorage.hgNightStyle 应该是 scene 或 cuteen;切完主题还能看到 document.querySelector('.Cuteen_DarkSky') 为 null(说明清理干净了)。档位选「关闭」时两种样式都不播动画,只切主题——这是预期行为。

5. 还有一个 hexo 的坑

改了 public/ 下的文件(哪怕只是临时 sed 调试),它的修改时间会比 source/ 新,hexo generate 会跳过复制,于是你以为改好了、其实线上还是旧的。遇到「源码明明改了但页面没变」,先删掉对应 public/js/... 再 generate,最省事。

评论区(Twikoo 私有部署)

借鉴:衍方(Twikoo 作者)的部署思路。本站改动:改为私有部署 + 同源反代,配置与安全项按本站服务器环境重写。

自建评论服务

国外那几家评论服务在国内加载慢、还可能被墙,备案后又要「可管可控」,干脆自己起一个 Twikoo:数据在自己服务器,前端只请求自己的域名(同源反代),不用额外证书。

服务器上 docker-compose.yml:

文件:服务器上的 docker-compose.yml(例如 /root/twikoo/docker-compose.yml,目录自己建)| 改法:新建文件,整段写入后把 <本地端口> 换成实际端口。注意这个文件不在博客目录里。

1
2
3
4
5
6
7
8
9
services:
twikoo:
image: imaegoo/twikoo:latest
container_name: twikoo
restart: always
ports:
- "127.0.0.1:<本地端口>:8080"
volumes:
- ./data:/app/data

<本地端口> 自己挑一个没被占用的端口(比如 6xxx~9xxx 里随便选),把这一行替换掉。

两条铁律:

  • 只绑 127.0.0.1:前面带 127.0.0.1: 就意味着只有本机能连,公网扫不到这个端口。
  • 不要写进公开的教程 / 截图里:端口只是内网细节,写出来等于告诉别人从哪儿找入口;外网访问一律走下面的 Nginx 反代(对外只有 443 + /twikoo/ 路径)。

保存后启动:

执行位置:服务器上存放 docker-compose.yml 的目录 | 作用:后台拉起 Twikoo 容器,ps 里 STATUS 显示 Up 就正常。

1
2
docker compose up -d
docker compose ps # STATUS 显示 Up 就正常

第一次启动会自动拉 imaegoo/twikoo 镜像;拉不动就给 Docker 配国内镜像加速。

Nginx 站点配置里加一段(放在 #REWRITE-START 之前):

文件:服务器 Nginx 的站点配置文件(宝塔面板里是「站点 → 配置文件」)| 改法:在 #REWRITE-START 之前插入这一段,<本地端口> 与 compose 里保持一致。

1
2
3
4
5
6
7
8
location ^~ /twikoo/ {
proxy_pass http://127.0.0.1:<本地端口>/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

nginx -t 通过后 nginx -s reload。验证:

执行位置:任意终端(本机或服务器都行)| 作用:POST 一次 GET_FUNC_VERSION,返回 {"code":0,...} 说明反代和容器都通了。

1
curl -i -X POST https://你的域名/twikoo/ -H "Content-Type: application/json" -d '{"event":"GET_FUNC_VERSION"}'

返回 {"code":0,...} 就通了。

[Blogroot]\_config.butterfly.yml:

文件:[Blogroot]/_config.butterfly.yml | 改法:顶层 comments: 把 use 改成 Twikoo,再新增顶层 twikoo: 段;envId 结尾的斜杠不能省。

1
2
3
4
5
6
7
8
9
comments:
use: Twikoo
text: true
lazyload: true

twikoo:
envId: https://你的域名/twikoo/ # 结尾的斜杠必须留,否则 location ^~ /twikoo/ 匹配不上
region:
visitor: true

管理员面板没有独立网址:评论框右下角那个小齿轮就是入口,第一次点开直接让你设密码(私有部署默认没有 TWIKOO_ADMIN 之类环境变量)。

忘记密码:改容器里的 /app/data/db.json,删掉 config.ADMIN_PASS 这一段,再回面板重设。数据全在 ./data 目录,记得纳入备份;想连评论数一起用,visitor: true 再把 comments.count 打开。

FPS 帧率监测(fomal 药丸版)

借鉴:LYX(Fomalhaut 整理)。本站改动:显示改成右下角药丸,六档状态与低性能模式阈值按本站实现调整。

右下角 FPS 药丸

用 requestAnimationFrame 数帧,每秒算一次,显示成右下角的小药丸:FPS 240 · 流畅,六档(极低/卡顿/偏低/一般/顺畅/流畅)。顺便驱动「低性能模式」:连续两次低于 35 帧就给 html 加 .low-perf,连续五次 50 帧以上再摘掉,方便在 custom.css 里给毛玻璃、动画、画布做降级。

新建 [Blogroot]\source\js\fps.js:

文件:[Blogroot]/source/js/fps.js | 改法:新建文件,整段写入;本站已有同名文件,改逻辑时在它的 stateOf() / loop() 里补全即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* 帧率检测(fomal 样式 + 本站低性能模式)
显示结构:<span class="fps-label">FPS</span><span class="fps-value">240</span><span class="fps-state" data-state="good">流畅</span>
fpson='1' 开启、'0' 关闭;面板里的「帧率监测」调 window.fpsSwitch(on)。 */
(function () {
var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || function (cb) {
return window.setTimeout(cb, 1000 / 60);
};
var node = null;
var frame = 0;
var lastTime = performance.now();
var warmupUntil = lastTime + 2000; // 首屏解析/解码天然掉帧,前 2 秒不计
var lowCount = 0;
var goodCount = 0;
var lowPerf = false;
var lastFp = -1;
var lastState = '';
var running = false;

function setLowPerf (on) {
if (lowPerf === on) return;
lowPerf = on;
document.documentElement.classList.toggle('low-perf', on);
}

// fomal 的六档:极低/卡顿/偏低/一般/顺畅/流畅
function stateOf (fps) {
if (fps <= 5) return ['极低', 'low'];
if (fps <= 15) return ['卡顿', 'low'];
if (fps <= 25) return ['偏低', 'warn'];
if (fps < 35) return ['一般', 'warn'];
if (fps <= 45) return ['顺畅', 'good'];
return ['流畅', 'good'];
}

function write (fps, status, state) {
if (!node) node = document.getElementById('fps');
if (!node) return;
var key = fps + '|' + state;
if (key === lastState) return;
lastState = key;
node.innerHTML = '<span class="fps-label">FPS</span><span class="fps-value">' + fps +
'</span><span class="fps-state" data-state="' + state + '">' + status + '</span>';
}

function loop (now) {
if (!running) return;
now = now || performance.now();
frame++;
var elapsed = now - lastTime;
if (elapsed >= 1000) {
var fps = Math.round((frame * 1000) / elapsed);
frame = 0;
lastTime = now;
if (now >= warmupUntil) {
var st = stateOf(fps);
write(fps, st[0], st[1]);
if (fps < 35) { lowCount++; goodCount = 0; } else if (fps >= 50) { goodCount++; lowCount = 0; } else { lowCount = 0; goodCount = 0; }
if (lowCount >= 2) setLowPerf(true);
if (goodCount >= 5) setLowPerf(false);
}
}
rAF(loop);
}

function start () {
if (running) return;
running = true;
frame = 0;
lastTime = performance.now();
warmupUntil = lastTime + 1200;
lastState = '';
if (node) node.style.display = '';
rAF(loop);
}

function stop () {
running = false;
lastState = '';
setLowPerf(false);
if (node) {
node.innerHTML = '';
node.style.display = 'none';
}
}

window.fpsSwitch = function (on) {
window.localStorage.setItem('fpson', on ? '1' : '0');
if (on) start(); else stop();
};

document.addEventListener('visibilitychange', function () { if (document.hidden) running = false; else if (window.localStorage.getItem('fpson') !== '0') start(); });

if (window.localStorage.getItem('fpson') !== '0') start();
})();

[Blogroot]\source\css\custom.css 追加药丸样式:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
html #fps, html[data-theme] #fps {
--fps-bg: rgba(232,242,246,.88); --fps-fg: #283c45; --fps-muted: #65757b;
--fps-border: rgba(61,91,104,.18); --fps-good: #267d72; --fps-warn: #a0740d; --fps-low: #df2039;
box-sizing: border-box; position: fixed;
right: 10px; bottom: 6px; left: auto;
z-index: 1919810; height: 30px; padding: 0 9px; width: max-content;
display: flex; align-items: center;
border: 1px solid var(--fps-border); border-radius: 9px;
background: var(--fps-bg); color: var(--fps-fg);
font-size: 13px; line-height: 1; font-weight: 500; white-space: nowrap;
box-shadow: 0 2px 8px rgba(15,35,45,.06); pointer-events: none; user-select: none;
}
html[data-theme="dark"] #fps {
--fps-bg: rgba(18,29,35,.88); --fps-fg: #dce9ef; --fps-muted: #9aacb6;
--fps-border: rgba(192,219,232,.16); --fps-good: #75d2c5; --fps-warn: #f0cb68; --fps-low: #ff8a95;
}
#fps:empty { visibility: hidden; }
#fps .fps-label { font-size: 10px; letter-spacing: .6px; color: var(--fps-muted); }
#fps .fps-value { min-width: 3ch; margin: 0 6px; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-variant-numeric: tabular-nums; font-weight: 600; text-align: right; }
#fps .fps-state { min-width: 2.6em; font-size: 12px; }
#fps .fps-state::before { content: "·"; margin-right: 5px; color: var(--fps-muted); }
#fps .fps-state[data-state="good"] { color: var(--fps-good); }
#fps .fps-state[data-state="warn"] { color: var(--fps-warn); }
#fps .fps-state[data-state="low"] { color: var(--fps-low); }
@media (max-width: 600px) {
html #fps, html[data-theme] #fps { height: 28px; padding: 0 8px; border-radius: 8px; }
}

[Blogroot]\_config.butterfly.yml 的 inject:

文件:[Blogroot]/_config.butterfly.yml | 改法:inject.head 加 <span id="fps"></span> 容器、inject.bottom 加脚本,两句分别放进对应列表。

1
2
3
4
5
inject:
head:
- <span id="fps"></span> # FPS 容器
bottom:
- <script async src="/js/fps.js?v=1"></script> # FPS

想随时开关:控制台执行 fpsSwitch(false) 关、fpsSwitch(true) 开,状态存在 localStorage.fpson;也可以接到美化设置面板里做一个开关行。

wowjs 进场动画

借鉴:Fomalhaut(猕猴桃)。本站改动:插件与 CDN 资源改为本地加载,动画时长与 PJAX 重载按本站流程调整。

滚动入场动画

主题自带 wowjs 支持,用的是 animate.css + wow.js,给指定 class 的元素加滚动入场动画。

先装插件(它把配置项注册进 Butterfly):

执行位置:博客根目录终端 | 作用:安装 wowjs 插件(wowjs: 配置由它读取并注入页面)。

1
npm install hexo-butterfly-wowjs --save

[Blogroot]\_config.butterfly.yml:

文件:[Blogroot]/_config.butterfly.yml | 改法:新增顶层 wowjs: 段;animateitem.class 填元素自身的 class(不带点),想加多个就继续往列表里加 - class/style。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
wowjs:
enable: true # 总开关
priority: 10 # 过滤器优先级
mobile: false # 移动端是否启用(移动端本来就容易掉帧,建议关)
animateitem:
- class: recent-post-item # 必填:要加动画的元素的 class
style: animate__zoomIn # 必填:animate.css 的动画名
duration: 1s # 可选
delay: 0ms # 可选
offset: 200px # 可选:离视口多远开始播放
iteration: 1 # 可选:播放次数
animate_css: https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/animate.min.css
wow_js: https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow.min.js
wow_init_js: https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow_init.js

几个注意点:

  • animateitem 的 class 填的是元素自身的 class,不用带点;首页卡片就是 recent-post-item。
  • 开了 PJAX 的博客,切页后新内容不会自动重新 new WOW().init()。要么在 pjax:complete 里手动执行一次,要么只对首页这类会整页重载的页面开动画。
  • 三条 CDN 都是 npm.elemecdn.com(国内可直连)。如果哪天访问慢,把三个文件下到 source/css、source/js,再改成本地路径即可——和「FontAwesome 图标本地化」那一节是同一套思路。

右键菜单(fomal 版)

原文作者:Fomalhaut(猕猴桃) 链接:https://www.fomal.cc/posts/d739261b.html

自定义右键菜单

默认右键菜单样式比较素,而且手机上长按会误触。换成 fomal 那套:圆形毛玻璃面板、图标 + 文字、滑入动画,顺带把「选择文字后复制/搜索」「粘贴」「回到顶部」「切换昼夜」「阅读模式」「打印」都收进来。

完整实现约 30KB,右键菜单 + 听话鼠标 + 下拉猫猫三合一放在同一个文件里,代码原样贴在下面(收在折叠块里,不需要时不用展开)。

先管放置和注入,代码在后面的代码块里。

把它放到 [Blogroot]\source\js\fomal\cursor.js,然后在 [Blogroot]\_config.butterfly.yml 的 inject.bottom 里排在 jQuery 之后:

文件:[Blogroot]/_config.butterfly.yml | 改法:在 inject.bottom 里把 cursor.js 排在 jquery.min.js 之后;同时把旧的 rightmenu.js、cat.js 两行注释掉,否则两套菜单会叠。

1
2
3
4
inject:
bottom:
- <script defer src="/js/jquery.min.js?v=1"></script>
- <script defer src="/js/fomal/cursor.js?v=1"></script> #右键菜单/鼠标特效

原来的 source\js\rightmenu.js、source\js\cat.js 两个注入要注释掉,否则两套菜单叠在一起。

完整 cursor.js(新建 [Blogroot]\source\js\fomal\cursor.js,整段复制进去):

文件:[Blogroot]/source/js/fomal/cursor.js | 改法:新建文件,整段写入;本站 source/js/fomal/cursor.js 已是这份三合一实现,跟着改时用已有文件对照,别新建第二份。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
/* ============================================================================
* modules/cursor.js —— 鼠标相关:右键菜单 / 小猫咪 / 听话鼠标
* ----------------------------------------------------------------------------
* 本文件由 source/js/fomal.js 拆出(2026-10-03 屎山重构)。
* 【重要】这里故意不套 IIFE:主题 pug 模板里有大量内联 onclick="xxx()",
* 以及别的脚本会直接调全局函数,所以本文件里的声明必须留在全局作用域。
* ----------------------------------------------------------------------------
* 包含的模块(括号内为拆分前在 fomal.js 里的行号):
* · 小猫咪(529-752)—— 页面右下角跟着鼠标走的小猫 + 整点报时气泡(.neko)
* · 右键菜单(756-1063)—— 自定义右键菜单(rmf 对象是菜单项表,popupMenu 负责拼 HTML)
* · 听话鼠标(1337-1436)—— class Cursor:鼠标指针带缓动拖尾、hover 可点元素时变形
* ----------------------------------------------------------------------------
* 三个都跟"指针"有关,所以放一起;其实互相独立,可以单独删。
* 加载方式:_config.fomalhaut.yml 的 inject.bottom 列表里以 <script defer> 引用。
* ----------------------------------------------------------------------------
* 【本文件目录】共 12 个顶层声明(行号可能随后续编辑漂移,找不到就 Ctrl+F 搜函数名)
* 263 setMask()
* 282 insertAtCursor(myField, myValue)
* 314 rmf
* 368 popupMenu()
* 500 box
* 502 addLongtabListener(target, callback)
* 537 mouseMode
* 538 changeMouseMode()
* 574 CURSOR
* 578 getStyle2
* 588 map
* 602 Cursor
* ========================================================================== */

/* ------------------------------ 小猫咪 ------------------------------ */
// 独立于右键菜单 mouse 偏好;缺失的新设置默认开启,不重置旧设置。
var nekoEnabled = localStorage.getItem('nekoOn') !== '0';
function setNekoEnabled(enabled) {
nekoEnabled = !!enabled;
document.documentElement.classList.toggle('beauty-neko-off', !nekoEnabled);
if (typeof nekoState === 'undefined' || !nekoState) return;
if (!nekoEnabled) {
if (nekoState.raf !== null) cancelAnimationFrame(nekoState.raf);
nekoState.raf = null;
clearInterval(window.__nekoClockTimer);
window.__nekoClockTimer = null;
nekoState.pointer = null;
nekoState.rect = null;
var cat = nekoElement();
nekoStyle(cat, 'display', 'none');
nekoClass(cat, 'hoverOn', false);
nekoClass(cat, 'showMsg', false);
} else {
if (!window.__nekoClockTimer) window.__nekoClockTimer = setInterval(nekoClockTick, 1000);
nekoClockTick();
nekoQueue(true, true);
}
}
/* 高频输入只记录最新值;统一在下一帧先读几何、再增量写入。 */
if (document.body.clientWidth > 992) {
var nekoState = { raf: null, geometryDirty: true, rectDirty: true, pointer: null,
cat: null, rope: null, rect: null, info: null, top: null, setting: null, styles: new WeakMap() };

function getBasicInfo() {
var ViewH = $(window).height();
var DocH = document.body.scrollHeight;
var ScrollTop = $(window).scrollTop();
var S_V = Math.max(0, DocH - ViewH);
return { ViewH: ViewH, DocH: DocH, ScrollTop: ScrollTop, S_V: S_V,
Band_H: S_V > 0 ? Math.max(0, Math.min(100, ScrollTop / S_V * 100)) : 0 };
}
function nekoElement() {
if (!nekoState.cat || !nekoState.cat.isConnected) {
nekoState.cat = document.querySelector('.neko');
nekoState.rect = null;
nekoState.rectDirty = true;
}
return nekoState.cat;
}
function nekoStyle(el, name, value) {
if (!el) return;
var values = nekoState.styles.get(el);
if (!values) { values = Object.create(null); nekoState.styles.set(el, values); }
// CSSOM 会规范化小数和单位,缓存目标值而不是反复比较序列化后的 style。
if (values[name] === value) return;
if (el.style[name] !== value) el.style[name] = value;
values[name] = value;
}
function nekoClass(el, name, enabled) {
if (el && el.classList.contains(name) !== enabled) el.classList.toggle(name, enabled);
}
function show(basicInfo) {
nekoStyle(nekoElement(), 'display', basicInfo.ScrollTop > 0.001 ? 'block' : 'none');
}
function nekoTimeMsg() {
var d = new Date();
var pad = function (n) { return (n < 10 ? '0' : '') + n; };
return pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
}
function nekoClockTick() {
if (!nekoEnabled || document.hidden) return;
var cat = nekoElement(), msg = nekoTimeMsg();
if (cat && cat.getAttribute('data-msg') !== msg) cat.setAttribute('data-msg', msg);
}
function nekoQueue(geometry, rect) {
nekoState.geometryDirty = nekoState.geometryDirty || !!geometry;
nekoState.rectDirty = nekoState.rectDirty || !!rect;
if (!nekoEnabled || nekoState.raf !== null || document.hidden) return;
nekoState.raf = requestAnimationFrame(nekoFlush);
}
function nekoHoverTick(clientX, clientY) {
if (!nekoEnabled) return;
nekoState.pointer = { x: clientX, y: clientY };
nekoQueue(false, false);
}
function nekoFlush() {
nekoState.raf = null;
if (!nekoEnabled || document.hidden) return;
var cat = nekoElement(), setting = nekoState.setting;
if (!cat || !setting) return;
// 读阶段:mousemove 不重读 scrollHeight,也不每次重读猫咪矩形。
var info = nekoState.geometryDirty || !nekoState.info ? getBasicInfo() : nekoState.info;
var rect = nekoState.rect;
if (nekoState.rectDirty && cat.style.display === 'block') {
var measured = cat.getBoundingClientRect();
rect = { left: measured.left, right: measured.right, top: measured.top, bottom: measured.bottom };
nekoState.rectDirty = false;
}
var height = info.Band_H * setting.zoom * info.ViewH * 0.01;
var top = height - 50;
if (rect && nekoState.top !== null) {
var delta = top - nekoState.top;
rect = { left: rect.left, right: rect.right, top: rect.top + delta, bottom: rect.bottom + delta };
}
var visible = info.ScrollTop > 0.001;
var p = nekoState.pointer;
var hover = !!(visible && rect && p && p.x >= rect.left && p.x <= rect.right && p.y >= rect.top && p.y <= rect.bottom);
// 写阶段:静态样式只在插件初始化时写,滚动仅更新高度、位置和状态。
nekoStyle(nekoState.rope, 'height', height + 'px');
nekoStyle(cat, 'top', top + 'px');
show(info);
nekoClass(cat, 'showMsg', visible && info.S_V > 0 && info.ScrollTop >= info.S_V - 1);
nekoClass(cat, 'hoverOn', hover);
if (hover) nekoClockTick();
nekoState.info = info;
nekoState.top = top;
nekoState.rect = visible ? rect : null;
nekoState.geometryDirty = false;
// 从 display:none 恢复后的真实 CSS 矩形在下一帧读,避免强制同步布局。
if (visible && !rect) nekoQueue(false, true);
}
setNekoEnabled(nekoEnabled);
document.addEventListener('mousemove', function (e) { nekoHoverTick(e.clientX, e.clientY); });
window.addEventListener('scroll', function () { nekoQueue(true, false); }, { passive: true });
window.addEventListener('resize', function () { nekoQueue(true, true); }, { passive: true });
window.addEventListener('mouseout', function (e) {
if (!e.relatedTarget) { nekoState.pointer = null; nekoQueue(false, false); }
});
document.addEventListener('visibilitychange', function () {
if (document.hidden) {
if (nekoState.raf !== null) cancelAnimationFrame(nekoState.raf);
nekoState.raf = null;
} else { nekoClockTick(); nekoQueue(true, true); }
});
if (typeof ResizeObserver !== 'undefined') {
nekoState.observer = new ResizeObserver(function () { nekoQueue(true, true); });
nekoState.observer.observe(document.body);
}
// 猫咪不挡下方按钮;点击只有在下方没有控件时才回顶部。
var nekoHitSelector = "a, button, input, select, textarea, label, summary, [onclick], [role='button'], [role='link'], #rightside, .search-mask, .search-dialog, #local-search, .neko, #myscoll";
function nekoToTop() {
if (!nekoEnabled) return;
if (window.btf && typeof btf.scrollToDest === 'function') btf.scrollToDest(0, 500);
else $('html, body').animate({ scrollTop: 0 }, 500);
}
document.addEventListener('click', function (e) {
var cat = nekoElement();
if (!nekoEnabled || !cat || cat.style.display !== 'block') return;
var r = cat.getBoundingClientRect();
if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) return;
var hit = document.elementFromPoint(e.clientX, e.clientY);
if (hit && $(hit).closest(nekoHitSelector).length) return;
nekoToTop();
});
(function ($) {
$.fn.nekoScroll = function (option) {
var setting = $.extend({ top: '0', scroWidth: '6px', z_index: 9999, zoom: 0.9,
borderRadius: '5px', right: '55.6px',
nekoImg: '/img/neko.png' }, option);
if (!this.length) return this;
var cat = nekoElement();
if (!cat) {
cat = document.createElement('div');
cat.className = 'neko';
if (setting.nekoname) cat.id = setting.nekoname;
cat.setAttribute('data-msg', nekoTimeMsg());
this.after(cat);
}
nekoState.cat = cat;
nekoState.rope = this[0];
nekoState.setting = setting;
nekoState.styles = new WeakMap();
nekoState.top = Number.isFinite(parseFloat(cat.style.top)) ? parseFloat(cat.style.top) : null;
nekoState.rect = null;
this.css({ position: 'fixed', width: setting.scroWidth, top: setting.top,
'z-index': setting.z_index, 'background-color': setting.bgcolor,
'border-radius': setting.borderRadius, right: setting.right,
'background-image': '-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.1) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.1) 50%, rgba(255, 255, 255, 0.1) 75%, transparent 75%, transparent)',
'background-size': 'contain' });
$(cat).css({ position: 'fixed', 'z-index': setting.z_index * 10,
right: setting.right, 'background-image': 'url(' + setting.nekoImg + ')' });
this.off('click.nekoScroll').on('click.nekoScroll', nekoToTop);
$(cat).off('click.nekoScroll').on('click.nekoScroll', nekoToTop);
if (!nekoEnabled) nekoStyle(cat, 'display', 'none');
nekoQueue(true, true);
return this;
};
})(jQuery);
$(document).ready(function () {
$('#myscoll').nekoScroll({ bgcolor: 'rgb(0 0 0 / .5)', borderRadius: '2em', zoom: 0.9 });
nekoClockTick();
});
document.addEventListener('pjax:complete', function () {
$('#myscoll').nekoScroll(nekoState.setting || {});
nekoClockTick();
nekoQueue(true, true);
});
}

/* 小猫咪 end */

/* ------------------------------ 右键菜单 ------------------------------ */
/* 原 fomal.js 756-1063 行,原样搬运,未改逻辑 */
/* 右键菜单 start */
function setMask() {
//设置遮罩
if (document.getElementsByClassName("rmMask")[0] != undefined)
return document.getElementsByClassName("rmMask")[0];
mask = document.createElement('div');
mask.className = "rmMask";
mask.style.width = window.innerWidth + 'px';
mask.style.height = window.innerHeight + 'px';
mask.style.background = '#fff';
mask.style.opacity = '.0';
mask.style.position = 'fixed';
mask.style.top = '0';
mask.style.left = '0';
mask.style.zIndex = 998;
document.body.appendChild(mask);
document.getElementById("rightMenu").style.zIndex = 19198;
return mask;
}

function insertAtCursor(myField, myValue) {

//IE 浏览器
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
sel.select();
}

//FireFox、Chrome等
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;

// 保存滚动条
var restoreTop = myField.scrollTop;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);

if (restoreTop > 0) {
myField.scrollTop = restoreTop;
}

myField.focus();
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
} else {
myField.value += myValue;
myField.focus();
}
}

let rmf = {};
rmf.showRightMenu = function (isTrue, x = 0, y = 0) {
let $rightMenu = $('#rightMenu');
$rightMenu.css('top', x + 'px').css('left', y + 'px');

if (isTrue) {
$rightMenu.show();
} else {
$rightMenu.hide();
}
}

rmf.copyWordsLink = function () {
let url = window.location.href
let txa = document.createElement("textarea");
txa.value = url;
document.body.appendChild(txa)
txa.select();
document.execCommand("Copy");
document.body.removeChild(txa);
}
rmf.switchReadMode = function () {
const $body = document.body
$body.classList.add('read-mode')
const newEle = document.createElement('button')
newEle.type = 'button'
newEle.className = 'fas fa-sign-out-alt exit-readmode'
$body.appendChild(newEle)

function clickFn() {
$body.classList.remove('read-mode')
newEle.remove()
newEle.removeEventListener('click', clickFn)
}

newEle.addEventListener('click', clickFn)
}

//复制选中文字
rmf.copySelect = function () {
document.execCommand('Copy', false, null);
}

//回到顶部
rmf.scrollToTop = function () {
var menus = document.getElementsByClassName("menus_items");
if (menus && menus[1]) menus[1].setAttribute("style", "");
var nameBox = document.getElementById("name-container");
if (nameBox) nameBox.setAttribute("style", "display:none");
var mobileMask = document.getElementById("mobile-menu-mask");
if (mobileMask) mobileMask.classList.remove("open");
if (window.btf && typeof btf.scrollToDest === "function") {
btf.scrollToDest(0, 500);
} else {
window.scrollTo({ top: 0, behavior: "smooth" });
}
}

document.body.addEventListener('touchmove', function () {

}, { passive: false });

function popupMenu() {
window.oncontextmenu = function (event) {
// if (event.ctrlKey) return true;

// 当关掉自定义右键时候直接返回
if (mouseMode == "off") return true;

$('.rightMenu-group.hide').hide();
if (document.getSelection().toString()) {
$('#menu-text').show();
}
if (document.getElementById('post')) {
$('#menu-post').show();
} else {
if (document.getElementById('page')) {
$('#menu-post').show();
}
}
var el = window.document.body;
el = event.target;
var a = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/
if (a.test(window.getSelection().toString()) && el.tagName != "A") {
$('#menu-too').show()
}
if (el.tagName == 'A') {
$('#menu-to').show()
rmf.open = function () {
if (el.href.indexOf("http://") == -1 && el.href.indexOf("https://") == -1 || el.href.indexOf("yisous.xyz") != -1) {
pjax.loadUrl(el.href)
}
else {
location.href = el.href
}
}
rmf.openWithNewTab = function () {
window.open(el.href);
// window.location.reload();
}
rmf.copyLink = function () {
let url = el.href
let txa = document.createElement("textarea");
txa.value = url;
document.body.appendChild(txa)
txa.select();
document.execCommand("Copy");
document.body.removeChild(txa);
}
} else if (el.tagName == 'IMG') {
$('#menu-img').show()
rmf.openWithNewTab = function () {
window.open(el.src);
// window.location.reload();
}
rmf.click = function () {
el.click()
}
rmf.copyLink = function () {
let url = el.src
let txa = document.createElement("textarea");
txa.value = url;
document.body.appendChild(txa)
txa.select();
document.execCommand("Copy");
document.body.removeChild(txa);
}
rmf.saveAs = function () {
var a = document.createElement('a');
var url = el.src;
var filename = url.split("/")[-1];
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
} else if (el.tagName == "TEXTAREA" || el.tagName == "INPUT") {
$('#menu-paste').show();
rmf.paste = function () {
navigator.permissions
.query({
name: 'clipboard-read'
})
.then(result => {
if (result.state == 'granted' || result.state == 'prompt') {
//读取剪贴板
navigator.clipboard.readText().then(text => {
// console.log(text)
insertAtCursor(el, text)
})
} else {
Snackbar.show({
text: '请允许读取剪贴板!',
pos: 'top-center',
showAction: false,
})
}
})
}
}
let pageX = event.clientX + 10;
let pageY = event.clientY;
let rmWidth = $('#rightMenu').width();
let rmHeight = $('#rightMenu').height();
if (pageX + rmWidth > window.innerWidth) {
pageX -= rmWidth + 10;
}
if (pageY + rmHeight > window.innerHeight) {
pageY -= pageY + rmHeight - window.innerHeight;
}
mask = setMask();
// 滚动消失的代码和阅读进度有冲突,因此放到readPercent.js里面了
$(".rightMenu-item").click(() => {
$('.rmMask').attr('style', 'display: none');
})
$(window).resize(() => {
rmf.showRightMenu(false);
$('.rmMask').attr('style', 'display: none');
})
mask.onclick = () => {
$('.rmMask').attr('style', 'display: none');
}
rmf.showRightMenu(true, pageY, pageX);
$('.rmMask').attr('style', 'display: flex');
return false;
};

window.addEventListener('click', function () {
rmf.showRightMenu(false);
});
}
if (!(navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
popupMenu()
}
const box = document.documentElement

function addLongtabListener(target, callback) {
let timer = 0 // 初始化timer

target.ontouchstart = () => {
timer = 0 // 重置timer
timer = setTimeout(() => {
callback();
timer = 0
}, 380) // 超时器能成功执行,说明是长按
}

target.ontouchmove = () => {
clearTimeout(timer) // 如果来到这里,说明是滑动
timer = 0
}

target.ontouchend = () => { // 到这里如果timer有值,说明此触摸时间不足380ms,是点击
if (timer) {
clearTimeout(timer)
}
}
}

addLongtabListener(box, popupMenu)

// 全屏
rmf.fullScreen = function () {
if (document.fullscreenElement) document.exitFullscreen();
else document.documentElement.requestFullscreen();
}

// 右键开关
if (localStorage.getItem("mouse") == undefined) {
localStorage.setItem("mouse", "on");
}
var mouseMode = localStorage.getItem("mouse");
function changeMouseMode() {
if (localStorage.getItem("mouse") == "on") {
mouseMode = "off";
localStorage.setItem("mouse", "off");
debounce(function () {
fomalNotify({
title: "切换右键模式成功🍔",
message: "当前鼠标右键已恢复为系统默认!",
position: 'top-left',
offset: 50,
showClose: true,
type: "success",
duration: 5000
})
}, 300);
} else {
mouseMode = "on";
localStorage.setItem("mouse", "on");
debounce(function () {
fomalNotify({
title: "切换右键模式成功🍔",
message: "当前鼠标右键已更换为网站指定样式!",
position: 'top-left',
offset: 50,
showClose: true,
type: "success",
duration: 5000
})
}, 300);
}
}
/* 右键菜单 end */

/* ------------------------------ 听话鼠标 ------------------------------ */
/* 原 fomal.js 1337-1436 行;位移分层、目标按需识别、空闲停帧。 */
/* 听话鼠标 start */
var CURSOR;

Math.lerp = (a, b, n) => (1 - n) * a + n * b;

const getStyle2 = (el, attr) => {
try {
return window.getComputedStyle
? window.getComputedStyle(el)[attr]
: el.currentStyle[attr];
} catch (e) { }
return "";
};

// 为了屏蔽异步加载导致无法读取颜色值,这里统一用哈希表预处理
const map = new Map();
map.set('red', "rgb(239, 90, 90)"); // 珊瑚红 #EF5A5A
map.set('orange', "rgb(215, 146, 77)"); // 暖杏橙 #D7924D
map.set('yellow', "rgb(196, 166, 74)"); // 蜂蜜金 #C4A64A
map.set('green', "rgb(57, 197, 187)"); // 青绿 #39C5BB
map.set('puregreen', "rgb(77, 175, 135)"); // 玉石绿 #4DAF87
map.set('blue', "rgb(74, 156, 199)"); // 晴空蓝 #4A9CC7
map.set('heoblue', "rgb(97, 106, 209)"); // 柔靛蓝 #616AD1(2026-10-14:色相 224°→235°,与晴空蓝拉开)
map.set('matcha', "rgb(102, 179, 77)"); // 抹茶绿 #66B34D(2026-10-14 新增:补 80°–150° 黄绿档,色相 105°)
map.set('darkblue', "rgb(113, 133, 156)"); // 雾蓝灰 #71859C
map.set('purepurple', "rgb(147, 90, 205)"); // 紫罗兰 #935ACD
map.set('pink', "rgb(237, 112, 155)"); // 樱花粉 #ED709B
// 下架的预设保留存储键迁移;首屏、鼠标与设置面板采用同一规则。
function normalizeThemePreset(c) {
if (c === 'purple') return 'purepurple';
if (c === 'gray' || c === 'black') return 'darkblue';
return c;
}
class Cursor {
constructor() {
this.enabled = localStorage.getItem('cursorOn') !== '0';
this.pos = { curr: null, prev: null };
this.pointerCache = new WeakMap();
this.controlCache = new WeakMap();
this.ancestorPointerCache = new WeakMap();
this.__raf = null;
this.__hoverDirty = false;
this.create();
this.init();
}

move(left, top) {
const value = 'translate3d(' + left + 'px, ' + top + 'px, 0)';
if (this.__transform !== value) {
this.layer.style.transform = value;
this.__transform = value;
}
}

create() {
if (!this.cursor) {
// 位移与 #cursor.hover/active 的 scale 分层:保留原来的 16px 尺寸与 0.2s 缩放。
this.layer = document.createElement('div');
this.layer.id = 'cursor-position';
Object.assign(this.layer.style, { position: 'fixed', left: '0px', top: '0px',
width: '16px', height: '16px', pointerEvents: 'none', zIndex: '10086' });
this.cursor = document.createElement('div');
this.cursor.id = 'cursor';
this.cursor.classList.add('hidden');
this.cursor.style.left = '0px';
this.cursor.style.top = '0px';
this.layer.appendChild(this.cursor);
}
if (!this.layer.isConnected) document.body.appendChild(this.layer);
if (!this.scr) this.scr = document.createElement('style');
const display = this.enabled ? '' : 'none';
if (this.layer.style.display !== display) this.layer.style.display = display;
// 原地改样式,不移除;任何时候都不能露出文字区域的系统 I 形光标。
if (!this.scr.isConnected) document.body.appendChild(this.scr);
const color = map.get(normalizeThemePreset(localStorage.getItem('themeColor'))) || map.get('green');
if (this.color !== color) {
const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" width="8px" height="8px"><circle cx="4" cy="4" r="4" fill="' + color + '"/></svg>';
this.scr.textContent = '* {cursor: url("data:image/svg+xml,' + encodeURIComponent(svg) + '") 4 4, auto}';
this.color = color;
}
// 插入/替换 CSS 文本会重新创建 CSSStyleSheet;必须最后设置 disabled。
this.scr.disabled = !this.enabled;
}

setClass(name, enabled) {
if (this.cursor.classList.contains(name) !== enabled) this.cursor.classList.toggle(name, enabled);
}

isPointer(target) {
if (target && target.nodeType !== 1) target = target.parentElement;
if (!target || !target.isConnected) return false;
// 控件身份与 CSS 结果分开缓存:子元素往返不再重复 closest / 祖先样式查询。
let control = this.controlCache.get(target);
if (control === undefined) {
control = target.closest('a[href], button, summary, label, input[type="button"], input[type="submit"], input[type="reset"], [onclick], [role="button"], [role="link"], .wb-control > span');
this.controlCache.set(target, control);
}
// WinBox 的标题栏按钮本来就是 cursor:pointer;标题和缩放边缘不走此快路径。
// disabled 读当前值,不能把已禁用按钮的旧结果复用。
if (control) return !control.disabled;
if (this.pointerCache.has(target)) return this.pointerCache.get(target);
let pointer = false;
const path = [];
for (let el = target; el; el = el.parentElement) {
if (this.ancestorPointerCache.has(el)) {
pointer = this.ancestorPointerCache.get(el);
break;
}
path.push(el);
if (getStyle2(el, 'cursor') === 'pointer') { pointer = true; break; }
}
// 保留原来的“任意祖先 pointer”语义;只在同一 hover / 样式版本共享祖先链。
for (const el of path) this.ancestorPointerCache.set(el, pointer);
this.pointerCache.set(target, pointer);
return pointer;
}

invalidatePointer(hitTest, clearCache = true) {
if (!this.enabled) return;
// 观察器可能在一帧内多次投递:这里只标脏,统一在 render 重建一次。
this.__pointerInvalid = this.__pointerInvalid || clearCache;
this.__hoverDirty = true;
this.__hitTest = this.__hitTest || !!hitTest;
if (this.pos.curr) this.start();
}

fpsOutputNode(node) {
if (node.nodeType === 3) return true;
if (node.nodeType !== 1 || node.tagName !== 'SPAN' || !node.getAttributeNames) return false;
if (![...node.childNodes].every(child => child.nodeType === 3)) return false;
const name = node.getAttribute('class');
const attrs = node.getAttributeNames().sort().join(',');
if (name === 'fps-label' || name === 'fps-value') return attrs === 'class';
if (name !== 'fps-state') return false;
if (attrs === 'class,data-state') return /^(?:good|warn|low)$/.test(node.getAttribute('data-state') || '');
// 兼容仍可能被缓存的旧版 reading.js:它给状态 span 内联写 color。
return attrs === 'class,style' &&
/^\s*color\s*:\s*(?:#bd0000|red|orange|#9338e6|#08b7e4|#39c5bb)\s*;?\s*$/i.test(node.getAttribute('style'));
}

pointerMutation(record) {
const target = record.target;
if (target === this.scr || this.scr.contains(target) ||
target === this.layer || this.layer.contains(target)) return 0;
// 精确排除已知纯装饰数据;不能泛化为忽略所有 class / style / 文本变化。
if (record.type === 'attributes' && record.attributeName === 'data-msg' &&
target.nodeType === 1 && target.classList.contains('neko')) return 0;
const element = target.nodeType === 1 ? target : target.parentElement;
const fps = element && element.closest('#fps');
if (fps) {
if (record.type === 'attributes' && record.attributeName === 'title' && target === fps) return 0;
// 只豁免计数器已知的纯文字 / 着色 span 输出,未知控件或重排仍全失效。
// 输出宽度变化可能改变命中元素,因此仍需重查位置。
if (record.type === 'childList' && target === fps && record.addedNodes && record.removedNodes &&
[...record.addedNodes, ...record.removedNodes].every(node => this.fpsOutputNode(node))) return 1;
if (record.type === 'characterData' && (element === fps ||
(element.parentElement === fps && this.fpsOutputNode(element)))) return 1;
}
return 2;
}

refresh() {
this.create();
this.setClass('active', false);
this.invalidatePointer(true);
// 不重绑事件、不重置位置、不创建第二条动画链;样式节点始终留在 DOM。
}

setEnabled(enabled) {
this.enabled = !!enabled;
this.create();
if (!this.enabled) {
this.pause();
this.pos.curr = this.pos.prev = null;
if (this.observer) this.observer.disconnect();
} else {
this.refresh();
this.observe();
}
}

observe() {
if (this.enabled && this.observer) {
this.observer.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true });
}
}

init() {
if (this.__bound) return;
this.__bound = true;
const trackTarget = e => {
if (!this.enabled) return;
if (this.target !== e.target) {
this.target = e.target;
this.__styleInvalid = true;
this.__hoverDirty = true;
}
};
document.addEventListener('mousemove', e => {
if (!this.enabled) return;
trackTarget(e);
this.pos.curr = { x: e.clientX - 8, y: e.clientY - 8 };
this.setClass('hidden', false);
this.start();
}, { passive: true });
document.addEventListener('mouseover', e => {
if (!this.enabled) return;
trackTarget(e);
// :hover / 兄弟选择器可能改变非语义区域的 cursor,下一帧更新 CSS 版本;
// 控件身份缓存不受纯 hover 切换影响。
this.__styleInvalid = true;
this.__hoverDirty = true;
if (this.pos.curr) this.start();
}, { passive: true });
document.addEventListener('mouseout', e => {
if (!this.enabled) return;
this.target = e.relatedTarget;
this.__styleInvalid = true;
this.__hoverDirty = true;
if (this.pos.curr) this.start();
}, { passive: true });
document.addEventListener('mouseenter', () => { if (this.enabled && this.pos.curr) this.setClass('hidden', false); });
document.addEventListener('mouseleave', () => this.pause());
window.addEventListener('blur', () => this.pause());
document.addEventListener('mousedown', () => { if (this.enabled) this.setClass('active', true); });
document.addEventListener('mouseup', () => this.setClass('active', false));
document.addEventListener('visibilitychange', () => { if (document.hidden) this.pause(); });
window.addEventListener('scroll', () => this.invalidatePointer(true), { passive: true });
window.addEventListener('resize', () => this.invalidatePointer(true), { passive: true });
document.addEventListener('pjax:complete', () => this.refresh());
document.addEventListener('load', e => {
if (e.target && e.target.tagName === 'LINK') this.invalidatePointer(true);
}, true);
if (typeof MutationObserver !== 'undefined') {
this.observer = new MutationObserver(records => {
if (!this.enabled) return;
let change = 0;
for (const record of records) {
change = Math.max(change, this.pointerMutation(record));
if (change === 2) break;
}
if (change) this.invalidatePointer(true, change === 2);
});
this.observe();
}
}

pause() {
if (this.__raf !== null) cancelAnimationFrame(this.__raf);
this.__raf = null;
this.setClass('hidden', true);
this.setClass('active', false);
this.setClass('hover', false);
this.target = null;
}

start() {
if (!this.enabled || this.__raf !== null || document.hidden || !this.pos.curr || this.cursor.classList.contains('hidden')) return;
this.__raf = requestAnimationFrame(() => { this.__raf = null; this.render(); });
}

render() {
const curr = this.pos.curr;
if (!this.enabled || !curr || document.hidden) return;
// 样式读取必须在 transform / class 写入之前完成,且每帧只处理最后一个目标。
if (this.__hoverDirty) {
if (this.__hitTest) {
const target = document.elementFromPoint(curr.x + 8, curr.y + 8);
if (target !== this.target) this.__styleInvalid = true;
this.target = target;
}
if (this.__pointerInvalid) this.controlCache = new WeakMap();
if (this.__pointerInvalid || this.__styleInvalid) {
this.pointerCache = new WeakMap();
this.ancestorPointerCache = new WeakMap();
}
this.__pointerInvalid = this.__styleInvalid = false;
const hover = this.isPointer(this.target);
this.__hoverDirty = false;
this.__hitTest = false;
this.setClass('hover', hover);
}
if (!this.pos.prev) this.pos.prev = { x: curr.x, y: curr.y };
const dx = curr.x - this.pos.prev.x, dy = curr.y - this.pos.prev.y;
const moving = Math.abs(dx) > 0.1 || Math.abs(dy) > 0.1;
this.pos.prev.x = moving ? Math.lerp(this.pos.prev.x, curr.x, 0.15) : curr.x;
this.pos.prev.y = moving ? Math.lerp(this.pos.prev.y, curr.y, 0.15) : curr.y;
this.move(this.pos.prev.x, this.pos.prev.y);
if (moving) this.start();
}
}

(() => {
CURSOR = new Cursor();
})();

/* 听话鼠标 end */

菜单项在 cursor.js 的 rightMenuItems 数组里,可以直接改。三项常见修复(都是实际踩过的):

  • 回到顶部没反应:主题里 rmf.scrollToTop 先取 #name-container 再删动画 class,非文章页这个节点是 null 会抛错,后面 btf.scrollToDest 根本执行不到。加空值保护:

文件:[Blogroot]/source/js/fomal/cursor.js | 改法:在 rmf.scrollToTop() 里用这两行替换原来直接操作 #name-container 的两行(取节点前先判空)。

1
2
if (el) el.classList.remove('name-container');
btf.scrollToDest(0, 500);
  • 「美化设置」点了没反应:[Blogroot]\themes\butterfly\layout\includes\rightmenu.pug 里 i.fas.fa-cog 那两行被 //- 注释掉了,只剩一个空的 <a>。把缩进恢复即可。
  • 复制选中内容的链接:菜单里用 rmf.copySelect() 即可,选中为空时提前 return,否则会复制出一个空字符串。

右侧按钮回到顶部进度

借鉴:Leonus(Fomalhaut 整理)。本站改动:在主题 main.js 里改为显示百分比,沿用本站右侧按钮样式。

百分比回顶

点击右下角回到顶部按钮,按钮里显示当前阅读进度百分比(滚到 95% 以上隐藏),滚动时实时更新。

[Blogroot]\themes\butterfly\source\js\main.js 里找到 scrollPercentElement.textContent = scrollPercent:

文件:[Blogroot]/themes/butterfly/source/js/main.js | 改法:找到 scrollPercentElement.textContent = scrollPercent(本站约在第 441 行),按「改后」整行替换;上面两行只是改前改后对照,不要一起粘进去。

1
2
3
4
// 改前
scrollPercentElement.textContent = scrollPercent
// 改后
scrollPercentElement.textContent = scrollPercent + '%'

[Blogroot]\themes\butterfly\layout\includes\rightside.pug 的 #go-up 里已经有 <span class="scroll-percent">,不用改结构。

[Blogroot]\source\css\custom.css 追加,让百分比和图标对齐:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
6
7
8
9
10
11
#rightside > div > button > i,
#rightside > div > a > i {
vertical-align: middle;
line-height: 1;
display: inline-block;
}
#rightside #go-up .scroll-percent {
font-size: 12px;
line-height: 35px;
letter-spacing: 0;
}

默认 #go-up 是宽高 35px 的方块,line-height: 35px 让百分比纵向居中;数字用 tabular-nums 更稳(不想加也行,跳动不明显)。

猫猫绳(下拉小猫)

借鉴:tzy 大佬(Fomalhaut 整理)。本站改动:与本站右键菜单合并进同一个 cursor.js,滚动阈值与位置重新调整。

下拉小猫

页面往下滚之后,右上角会垂下来一只小猫(就是那根「猫猫绳」),点它会平滑滚回顶部。

它和右键菜单在同一个文件里([Blogroot]\source\js\fomal\cursor.js),用的是 jQuery 插件的 $.fn.nekoScroll:

文件:[Blogroot]/source/js/fomal/cursor.js | 改法:替换 $(document).ready(...) 里 $('#myscoll').nekoScroll({...}) 的参数;锚点 #myscoll 主题已自带(themes/butterfly/layout/includes/head.pug 里那个空 #myscoll,第 79 行),没有就自己在模板里补一个 <div id="myscoll"></div>。

1
2
3
4
5
6
7
$('#myscoll').nekoScroll({
top: '0px',
right: '30px',
width: 70,
height: 70,
nekoImg: '/img/neko.png'
});

要点:

  • 图片放本地:把小猫图存到 [Blogroot]\source\img\neko.png,nekoImg 写 /img/neko.png。直接引外链(图床)一旦挂掉,猫就没了。
  • 挂载点:需要一个 #myscoll 锚点(随便一个空 div),猫是插在它旁边的;锚点不存在就不显示。
  • 显示时机:cursor.js 里判断 #myscoll 在视口外、且 scrollTop > 0.001 时才显示,回到页面顶部自动收起——避免一进首页就挂一只猫在右上角。
  • 点击动作:rmf.scrollToTop(),和右键菜单里的「回到顶部」是同一个函数,所以上一节那个空值保护对它同样有效。

顶部缝隙:APlayer 标记元素把页面顶下去 10px

那条 10px 亮带

现象:导航栏上方有一条 10px 左右、比别处更亮的横带,像遮罩没盖到最顶上。换主题色、调遮罩深浅都没用——因为它根本不是遮罩的问题。

根因:APlayer 初始化时会在 <body> 里塞一个零高度的标记元素:

说明:示意内容,不需要修改——这是 APlayer 初始化后 body 里实际出现的 DOM,用来对照现象。

1
<div class="aplayer aplayer-tag-marker"></div>

它是 position: relative; height: 0,但它带着 margin-top: 5px; margin-bottom: 5px。高度为 0 也有 margin,于是把后面所有兄弟元素(#body-wrap、#sidebar、#nav 的定位参照)整体往下推了 10px。

#page-header 从 y=10 开始,而它的 ::before(--mark-bg 那层遮罩)用的是 height: 100%,只会覆盖 header 自身那块区域,顶部这 10px 里露出来的是 #web_bg 的原图,没有遮罩 → 就是那条亮带。

验证方法(不用装任何工具):在本地起服务后,同一个域下建个临时页面,用 iframe 载入首页,读 body.children 的布局:

执行位置:浏览器 F12 控制台(在首页执行)| 作用:打印「高度为 0 却带 margin」的元素,确认那条亮带的来源。

1
2
3
4
5
6
7
// 简化版:在控制台对首页执行也一样
[...document.body.children].forEach((el, i) => {
const s = getComputedStyle(el);
if (s.position === 'relative' && parseFloat(s.height) === 0 && s.marginTop !== '0px') {
console.log(i, el.className, 'mt=' + s.marginTop, 'h=' + s.height);
}
});

会打印出 aplayer aplayer-tag-marker mt=5px h=0px。再看 #page-header 的 getBoundingClientRect().top 是 10 而不是 0,就坐实了。

修法:把这个标记元素和同源的背景元素全部压成 0,custom.css 加一段

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
6
7
8
9
/* APlayer 注入的零高度标记元素带 5px 上下 margin,会把整页顶下 10px,遮罩就盖不到最顶上 */
body > .aplayer,
body > .aplayer-tag-marker,
body > #an_music_bg {
margin: 0 !important;
padding: 0 !important;
line-height: 0 !important;
height: 0 !important;
}

修完之后 #page-header 的 rect.top 是 0,遮罩与 header 等高,亮带消失。

顺带提醒:判断「遮罩有没有生效」别只看颜色深浅,先量几何——#page-header 的 top 和 ::before 的 height 是否一致,比肉眼靠谱。

统一弹窗:一套卡片 + 最多 5 条

借鉴:Fomalhaut(猕猴桃)。本站改动:把站内三套提示统一到 fomalNotify,最多 5 条并接入美化面板。

把所有提示收进 fomalNotify

站上原本有三套提示各说各话:美化面板用 fomalNotify,性能模式用自己的 toast()(位置在右上、样式也不同),昼夜切换走主题的 Vue $notify / snackbar。同一个站点三种弹窗,看着就很乱。

目标:所有提示都走 [Blogroot]\source\js\fomal\notify.js 里的 fomalNotify(),样式统一、位置统一,并且最多同时在屏幕上留 5 条。

fomalNotify 的调用形式:

说明:调用示例(怎么用),不需要改文件——按这个参数在任意脚本里调 fomalNotify({...}) 就行。

1
2
3
4
5
6
7
8
9
fomalNotify({
title: '开灯啦🌞',
message: '当前已切换至白天模式',
type: 'success', // success / info / warning / error
position: 'top-left', // 也可以用 top-right
offset: 50, // 距视口边缘的像素
showClose: true,
duration: 4000 // ms,0 表示不自动关
});

加 5 条上限:在 notify.js 里维护一个存活列表,创建新卡片前先把超额的关掉。

文件:[Blogroot]/source/js/fomal/notify.js | 改法:在文件顶部(fomalNotify 定义之前)新增这两个声明和 evictOldest() 函数;本站这段已在第 92 行附近。

1
2
3
4
5
6
7
8
9
10
11
var MAX_LIVE = 5;
var live = [];

function evictOldest () {
while (live.length >= MAX_LIVE) {
var old = live.shift();
if (old && old.close) {
try { old.close(); } catch (e) {}
}
}
}

在 wrap.appendChild(box) 之前调 evictOldest();close() 里要把自己从列表移除,否则列表只增不减:

文件:[Blogroot]/source/js/fomal/notify.js | 改法:在已有的 close()(本站约第 130 行)开头补上「把自己从 live 里移除」这两行,后面的移除动画保持原样。

1
2
3
4
5
function close () {
var idx = live.indexOf(api);
if (idx !== -1) live.splice(idx, 1);
// ……原有的移除动画
}

最后把返回值和入列补上:

文件:[Blogroot]/source/js/fomal/notify.js | 改法:在创建卡片的收尾处换成这三行——先在 wrap.appendChild(box) 之前调 evictOldest(),再 live.push(api) 并返回 api。

1
2
3
var api = { close: close, box: box };
live.push(api);
return api;

暗色适配:卡片本身是浅色底,暗色主题下会白得刺眼,补一段

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
[data-theme="dark"] .fomal-notify { background: #252a35; border-color: #3a4150; box-shadow: 0 4px 18px 0 rgba(0, 0, 0, .5); }
[data-theme="dark"] .fomal-notify__title { color: #e8ecf3; }
[data-theme="dark"] .fomal-notify__content { color: #b9c2cf; }
[data-theme="dark"] .fomal-notify__close { color: #8b95a5; }
[data-theme="dark"] .fomal-notify__close:hover { color: #e8ecf3; }

把主题自带的昼夜提示也收过来:themes\butterfly\source\js\sun_moon.js 的 btfNightToast() 最前面加一个优先分支(保留原来的 Vue / snackbar 兜底,主题更新后不至于报错):

文件:[Blogroot]/themes/butterfly/source/js/sun_moon.js | 改法:在 btfNightToast()(本站约第 47 行)函数体最前面插入这段优先分支,原来的 Vue / snackbar 兜底留在后面不要删。

1
2
3
4
5
6
7
8
if (typeof window.fomalNotify === 'function') {
window.fomalNotify({
title: title, message: message,
position: 'top-left', offset: 50,
showClose: true, type: 'success', duration: 4000
});
return;
}

统一位置与时长:把 [Blogroot]\source\js\fomal\perf.js 里的 toast() 从右上角挪到左上角,和面板保持一致

文件:[Blogroot]/source/js/fomal/perf.js | 改法:把 toast() 里 position / offset / duration 三个参数改成下面这行(本站已改成 top-left),上一行只是改前对照。

1
2
// 改前:position: 'top-right', offset: 60, duration: 5200
position: 'top-left', offset: 50, duration: 4200

验证:控制台连发 6 条带 duration: 60000 的提示,屏幕上应该只剩 5 条,且最早的两条(第 1、2 条)已被淘汰,剩下的是第 2 ~ 6 条;暗色下卡片是 #252a35 深灰底,不是白块。

夜间霓虹灯字

借鉴:Fomalhaut(猕猴桃)。本站改动:配色接本站 CSS 变量,浅色模式强制关闭动画。

九色呼吸光晕

思路:浅色模式完全不加动效;暗色模式下给站点标题、副标题、文章信息分别套一条 text-shadow 关键帧动画,让光晕颜色循环流动。

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* 浅色模式不要任何光晕 */
[data-theme="light"] #site-name,
[data-theme="light"] #site-title,
[data-theme="light"] #site-subtitle,
[data-theme="light"] #post-info {
animation: none !important;
}

/* 暗色模式:三档光晕半径 */
[data-theme="dark"] #site-name,
[data-theme="dark"] #site-title {
animation: light_15px 10s linear infinite;
}
[data-theme="dark"] #site-subtitle {
animation: light_10px 10s linear infinite;
}
[data-theme="dark"] #post-info {
animation: light_5px 10s linear infinite;
}

关键帧长这样,0/12.5/25/37.5/43.75/62.5/75/87.5/100% 各一个颜色:

文件:[Blogroot]/source/css/custom.css | 改法:紧接上一段追加;light_10px / light_5px 按注释只改半径,颜色顺序保持一致。

1
2
3
4
5
6
7
8
9
10
11
12
@keyframes light_15px {
0% { text-shadow: 0 0 15px #f1ee47; }
12.5%{ text-shadow: 0 0 15px #11ee5e; }
25% { text-shadow: 0 0 15px #00e4f5; }
37.5%{ text-shadow: 0 0 15px #0051ff; }
43.75%{ text-shadow: 0 0 15px #f1ee47; }
62.5%{ text-shadow: 0 0 15px #b347f1; }
75% { text-shadow: 0 0 15px #ff6a00; }
87.5%{ text-shadow: 0 0 15px #ff2f92; }
100% { text-shadow: 0 0 15px #f1ee47; }
}
/* light_10px / light_5px 只把 15px 换成 10px / 5px,颜色顺序一致 */

两个容易踩的点:

  • 颜色别重复写在同一个百分比:网上流传的版本里 #f1ee47 和 #b347f1 都写在 50%,后写的覆盖前写的,黄色实际上永远不出现。要么把黄色挪到 43.75%(本文做法),要么删掉一条。
  • 小档位的光晕半径要跟着改:light_5px 里漏改一处 15px 会让光晕在那一瞬间突然膨胀,看着一跳一跳的。

无障碍兜底:系统开了「减少动效」就别闪了

文件:[Blogroot]/source/css/custom.css | 改法:再追加到末尾,放在霓虹灯规则之后。

1
2
3
@media (prefers-reduced-motion: reduce) {
#site-name, #site-title, #site-subtitle, #post-info { animation: none !important; }
}

另外,如果站点开了「性能模式」这类一键降级,不要用 html:not(.perf-lite)[data-theme="dark"] 这种前缀把它排除掉——两个元素的 text-shadow 动画几乎不花性能,但一旦被排除,很多人会开着性能模式却看不到效果,以为是没生效。

Hexo 8 / Butterfly 5.7.2 配置清单

大版本升级迁移

在 [Blogroot]\package.json 添加:

文件:[Blogroot]/package.json | 改法:在顶层对象里加 "engines" 键(这是一段对象片段,插进去时注意和前一项之间的逗号)。

1
"engines": { "node": ">=20.19.0" }

执行:

执行位置:博客根目录终端 | 作用:把 Hexo 固定到 8.1.2,然后清缓存重新生成,确认主题在新版本下能编过。

1
2
npm install hexo@8.1.2 --save-exact
hexo clean && hexo g

[Blogroot]\_config.butterfly.yml 配置键映射:

| 4.x | 5.x |
| —- | —- |
| local_search.enable: true | search.use: local_search |
| fancybox: true / medium_zoom | lightbox: fancybox |
| mathjax.enable: true | math.use: mathjax |
| sharejs.enable: true | share.use: sharejs |
| highlight_theme 等 6 个键 | code_blocks.theme / macStyle / copy / language / shrink / height_limit / word_wrap / fullpage |
| footer_bg | footer_img |
| footer.copyright: false | footer.copyright: { enable: false, version: false } |
| footer_beautify 徽标文案 | Hexo_v8.1.2 / Butterfly_v5.7.2 |

连字符键改成下划线键:

| 4.x | 5.x |
| —- | —- |
| font.global-font-size | font.global_font_size |
| font.code-font-size | font.code_font_size |
| font.font-family | font.font_family |
| font.code-font-family | font.code_font_family |
| beautify.title-prefix-icon | beautify.title_prefix_icon |
| beautify.title-prefix-icon-color | beautify.title_prefix_icon_color |
| hr_icon.icon-top | hr_icon.icon_top |

background 只填纯路径:

文件:[Blogroot]/_config.butterfly.yml | 改法:顶层 background: 只填纯路径,不要写 url(...),也不要带引号里的括号。

1
background: /img/bg.webp

[Blogroot]\themes\butterfly\layout\includes\layout.pug 补 #footer-wrap:

文件:[Blogroot]/themes/butterfly/layout/includes/layout.pug | 改法:核对 footer#footer 下是否有这两层;5.7.2 已自带,只是确认,不要重复添加。

1
2
3
footer#footer(style=footer_bg)
#footer-wrap
!=partial('includes/footer', {}, {cache: true})

[Blogroot]\themes\butterfly\layout\includes\layout.pug 删掉 4.x 手加的 third-party/search/index 那行。
模板判断改成:

文件:主题模板里 4.x 写成 if page.type === 'post' / is_post() 的那类判断(例如 themes/butterfly/layout/includes/header/nav.pug:8)| 改法:把条件换成 if globalPageType === 'post'。

1
if globalPageType === 'post'

文件:[Blogroot]/themes/butterfly/layout/page.pug(本站约第 13 行)| 改法:把页面标题的判断换成这两行,只有 top_img === false 的页面才渲染 h1.page-title。

1
2
if top_img === false && page.type != 'music' && page.title
h1.page-title= page.title

[Blogroot]\themes\butterfly\source\js\sun_moon.js 用 btf.activateDarkMode() / btf.activateLightMode() / btf.saveToLocal.set('theme', mode, 2),代码见第二章第 11 项。
[Blogroot]\source\css\custom.css 追加 5.x 双排适配,代码见本章第 28 项。
保持不动的挂载点:#recent-posts、.sticky_layout、.recent-post-item。
生成后检查:

执行位置:博客根目录终端 | 作用:清缓存重新生成,下一步去 public/ 里核对注入结果。

1
hexo clean && hexo g

在 public/index.html 中确认存在:footer-wrap、beian-row、rightMenu、main-hero-waves-area、loading-image-dot、recent-post-items。

改完怎么验证与部署

改完不要直接往服务器扔,按顺序走一遍,出错能马上定位在哪一步:

  1. 生成。博客根目录终端执行 hexo generate。命令跑完没报 FATAL 才算过,public/ 里会重新产出整站。
  2. 本地预览。hexo server(默认 http://localhost:4000,端口被占就 hexo s -p 4001)。逐节点开对应页面:首页看磁贴、轮播、多栏和侧栏卡片,文章页看备案、右键菜单、猫猫绳和 FPS 药丸,评论页发一条测试评论。
  3. 强制刷新 / 清缓存。改过 source/css/、source/js/ 的话,把 _config.butterfly.yml 里 inject 对应行的 ?v=xxx 版本号改一版(如 ?v=20261111a 换成 ?v=20261111b),再 Ctrl+F5 或开无痕窗口看;还不行就删掉 public/、.deletions 和浏览器里该站点的 Service Worker 缓存后重新生成。
  4. F12 查 404。Network 面板勾上 404 过滤、刷新一次,重点看 /css/custom.css、/js/fomal/*.js、/css/brinks.css、/font/*.woff2、/webfonts/*、/img/* 有没有红条——这些基本都是路径写错或文件没放进去。再看 Console,fomalNotify、Cursor、fpsSwitch 之类报 undefined 说明脚本没注入或顺序不对(脚本要排在 jQuery 之后)。
  5. 按原托管方式上传。Nginx / 宝塔:把 public/ 整个传上去;GitHub Pages:用 _config.yml 里的 deploy: type: git 再 hexo deploy;Vercel / Netlify:把仓库推上去,构建命令 hexo generate、输出目录 public,让它自动构建。上线后再强刷一次,确认线上版本号就是刚改的那版。

这篇已经把第 21 ~ 41 个魔改写完了,18544 字、阅读约 89 分钟,再往下堆就不好翻了。
后面新的魔改我会单独开一篇《hexo魔改教程(四)》,本篇不再追加——想跟更新的部分,从系列导航里找(四)就行。