配置异常简单,下载油猴插件,谷歌浏览器开fq或者下载安装包
点击油猴—>添加新脚本->ctrl+a再ctrl+v然后ctrl+s就行了
// ==UserScript==
// @name 网页字体更换器
// @namespace https://github.com/font-switcher
// @version 6.1.0
// @description 为任意网站更换字体,边缘吸附按钮自动收起,每个网站独立配置,支持字号/加粗设置,支持自定义字体,支持更多外观设置
// @author FontSwitcher
// @match *://*/*
// @grant GM_addStyle
// @grant GM_getValue
// @grant GM_setValue
// @run-at document-idle
// @license MIT
// ==/UserScript==
(function () {
'use strict';
// ==================== 默认常量 ====================
const DEFAULT_BTN_SIZE = 42;
const COLLAPSED_VISIBLE = 6;
const HOVER_ZONE = 10;
const DEFAULT_IDLE_MS = 5000;
const DRAG_THRESHOLD = 4;
const PANEL_W = 360;
const PANEL_MAX_H = 560;
const MARGIN = 8;
// ==================== 存储 ====================
const STORAGE_KEY_CUSTOM_FONTS = 'fontSwitcher_customFonts';
const STORAGE_KEY_GLOBAL_SETTINGS = 'fontSwitcher_globalSettings';
const CURRENT_HOST = location.hostname;
function siteKey(base) { return `${base}@${CURRENT_HOST}`; }
const STORAGE_KEY_ACTIVE_FONT = siteKey('fontSwitcher_activeFont');
const STORAGE_KEY_ENABLED = siteKey('fontSwitcher_enabled');
const STORAGE_KEY_BTN_POS = siteKey('fontSwitcher_btnPos');
const STORAGE_KEY_FONT_SETTINGS = siteKey('fontSwitcher_fontSettings');
function loadFromStorage(key, fallback) {
try {
if (typeof GM_getValue === 'function') {
const v = GM_getValue(key, null);
if (v !== null && v !== undefined) return v;
}
const raw = localStorage.getItem(key);
if (raw !== null) return JSON.parse(raw);
} catch (e) { /* 忽略 */ }
return fallback;
}
function saveToStorage(key, value) {
try {
if (typeof GM_setValue === 'function') GM_setValue(key, value);
localStorage.setItem(key, JSON.stringify(value));
} catch (e) { /* 忽略 */ }
}
function saveBtnPosition() {
saveToStorage(STORAGE_KEY_BTN_POS, { side: btnSide, y: btnY });
}
// ==================== 全局设置 ====================
const DEFAULT_GLOBAL_SETTINGS = {
btnSize: 42, // 按钮大小 28~60
autoCollapse: true, // 自动吸附收起
idleMs: 5000, // 收起延迟
excludeInputs: false, // 排除输入框
toastDuration: 2000, // Toast 显示时长
};
let globalSettings = Object.assign({}, DEFAULT_GLOBAL_SETTINGS, loadFromStorage(STORAGE_KEY_GLOBAL_SETTINGS, {}));
function saveGlobalSettings() {
saveToStorage(STORAGE_KEY_GLOBAL_SETTINGS, globalSettings);
}
// 派生变量(从设置中读取)
let BTN_SIZE = globalSettings.btnSize || DEFAULT_BTN_SIZE;
let IDLE_MS = globalSettings.autoCollapse ? (globalSettings.idleMs || DEFAULT_IDLE_MS) : Infinity;
let COLLAPSED_SHIFT = BTN_SIZE - COLLAPSED_VISIBLE;
function refreshDerivedSettings() {
BTN_SIZE = globalSettings.btnSize || DEFAULT_BTN_SIZE;
IDLE_MS = globalSettings.autoCollapse ? (globalSettings.idleMs || DEFAULT_IDLE_MS) : Infinity;
COLLAPSED_SHIFT = BTN_SIZE - COLLAPSED_VISIBLE;
}
// ==================== 状态 ====================
let customFonts = loadFromStorage(STORAGE_KEY_CUSTOM_FONTS, []);
let activeFontValue = loadFromStorage(STORAGE_KEY_ACTIVE_FONT, '');
let isEnabled = loadFromStorage(STORAGE_KEY_ENABLED, true);
let fontSettings = loadFromStorage(STORAGE_KEY_FONT_SETTINGS, {});
const savedPos = loadFromStorage(STORAGE_KEY_BTN_POS, null);
let btnSide = (savedPos && savedPos.side) ? savedPos.side : 'right';
let btnY = (savedPos && typeof savedPos.y === 'number') ? savedPos.y : 60;
let panelVisible = false;
let btnCollapsed = false;
let idleTimer = null;
let isDragging = false;
let hasDragged = false;
let dragStartX = 0, dragStartY = 0;
let btnStartLeft = 0, btnStartTop = 0;
let previewStyleEl = null;
let expandedSettingsSet = new Set();
let settingsViewActive = false; // 设置视图是否激活
// ==================== 预置字体 ====================
const PRESET_FONTS = [
{ name: '默认(不替换)', value: '' },
{ name: '微软雅黑', value: '"Microsoft YaHei", "微软雅黑", sans-serif' },
{ name: '苹方', value: '"PingFang SC", "Helvetica Neue", sans-serif' },
{ name: '宋体', value: 'SimSun, "宋体", serif' },
{ name: '黑体', value: 'SimHei, "黑体", sans-serif' },
{ name: '楷体', value: 'KaiTi, "楷体", serif' },
{ name: '仿宋', value: 'FangSong, "仿宋", serif' },
{ name: '思源黑体', value: '"Source Han Sans SC", "Noto Sans SC", sans-serif' },
{ name: '思源宋体', value: '"Source Han Serif SC", "Noto Serif SC", serif' },
{ name: '文泉驿正黑', value: '"WenQuanYi Zen Hei", sans-serif' },
{ name: '霞鹜文楷', value: '"LXGW WenKai", sans-serif' },
{ name: '等线', value: 'DengXian, "等线", sans-serif' },
{ name: '华文黑体', value: '"STHeiti", sans-serif' },
{ name: '华文楷体', value: 'STKaiti, "华文楷体", serif' },
{ name: '华文宋体', value: 'STSong, "华文宋体", serif' },
{ name: '华文仿宋', value: 'STFangsong, "华文仿宋", serif' },
{ name: 'Arial', value: 'Arial, Helvetica, sans-serif' },
{ name: 'Times New Roman', value: '"Times New Roman", Times, serif' },
{ name: 'Georgia', value: 'Georgia, serif' },
{ name: 'Comic Sans MS', value: '"Comic Sans MS", cursive' },
{ name: 'Consolas', value: 'Consolas, "Courier New", monospace' },
{ name: 'Trebuchet MS', value: '"Trebuchet MS", Helvetica, sans-serif' },
{ name: 'Verdana', value: 'Verdana, Geneva, sans-serif' },
];
// ==================== 字体设置工具 ====================
function getFontSettings(fontValue) {
if (!fontValue) return null;
return fontSettings[fontValue] || null;
}
function setFontSettings(fontValue, settings) {
if (!fontValue) return;
fontSettings[fontValue] = settings;
saveToStorage(STORAGE_KEY_FONT_SETTINGS, fontSettings);
}
function removeFontSettings(fontValue) {
if (!fontValue) return;
delete fontSettings[fontValue];
saveToStorage(STORAGE_KEY_FONT_SETTINGS, fontSettings);
}
function hasNonDefaultSettings(fontValue) {
if (!fontValue) return false;
const s = fontSettings[fontValue];
if (!s) return false;
if (s.size) return true;
if (s.weight && s.weight !== '' && s.weight !== 'normal') return true;
return false;
}
// ==================== 样式注入 ====================
function buildStyles() {
return `
/* ========== 按钮 ========== */
#fs-trigger-btn {
position: fixed;
z-index: 2147483647;
width: ${BTN_SIZE}px;
height: ${BTN_SIZE}px;
border: none;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
font-size: ${Math.round(BTN_SIZE * 0.43)}px;
font-weight: bold;
cursor: pointer;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.45);
display: flex;
align-items: center;
justify-content: center;
user-select: none;
-webkit-user-select: none;
font-family: "Segoe UI", Arial, sans-serif !important;
touch-action: none;
opacity: 0.9;
transition: transform 0.35s cubic-bezier(0.4, 0, 0.2, 1),
box-shadow 0.2s ease,
opacity 0.25s ease,
border-radius 0.3s ease,
width 0.25s ease,
height 0.25s ease;
}
#fs-trigger-btn:hover {
box-shadow: 0 6px 24px rgba(102, 126, 234, 0.65);
opacity: 1;
}
#fs-trigger-btn .fs-btn-icon {
pointer-events: none;
line-height: 1;
font-size: ${Math.round(BTN_SIZE * 0.48)}px;
transition: opacity 0.2s;
}
/* 右侧吸附 */
#fs-trigger-btn.fs-side-right {
right: 0;
left: auto;
border-radius: ${BTN_SIZE / 2}px 0 0 ${BTN_SIZE / 2}px;
}
#fs-trigger-btn.fs-side-right.fs-collapsed {
transform: translateX(${COLLAPSED_SHIFT}px);
border-radius: 8px 0 0 8px;
pointer-events: none;
opacity: 0.5;
}
#fs-trigger-btn.fs-side-right.fs-collapsed .fs-btn-icon { opacity: 0; }
/* 左侧吸附 */
#fs-trigger-btn.fs-side-left {
left: 0;
right: auto;
border-radius: 0 ${BTN_SIZE / 2}px ${BTN_SIZE / 2}px 0;
}
#fs-trigger-btn.fs-side-left.fs-collapsed {
transform: translateX(-${COLLAPSED_SHIFT}px);
border-radius: 0 8px 8px 0;
pointer-events: none;
opacity: 0.5;
}
#fs-trigger-btn.fs-side-left.fs-collapsed .fs-btn-icon { opacity: 0; }
/* 拖拽中 */
#fs-trigger-btn.fs-dragging {
cursor: grabbing !important;
opacity: 1;
box-shadow: 0 8px 30px rgba(118, 75, 162, 0.7);
transform: scale(1.08) !important;
border-radius: 50% !important;
transition: box-shadow 0.15s, opacity 0.15s;
}
#fs-trigger-btn.fs-active {
opacity: 1;
box-shadow: 0 6px 24px rgba(118, 75, 162, 0.7);
}
@keyframes fs-btn-enter {
from { opacity: 0; transform: scale(0.5); }
to { opacity: 0.9; transform: scale(1); }
}
#fs-trigger-btn.fs-entering {
animation: fs-btn-enter 0.4s ease forwards;
}
/* ========== 遮罩 ========== */
#fs-overlay {
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
z-index: 2147483646;
background: transparent;
display: none;
}
#fs-overlay.fs-show { display: block; }
/* ========== 面板 ========== */
#fs-panel {
position: fixed;
z-index: 2147483647;
width: ${PANEL_W}px;
max-height: ${PANEL_MAX_H}px;
background: #ffffff;
border-radius: 16px;
box-shadow: 0 12px 48px rgba(0,0,0,0.18), 0 2px 8px rgba(0,0,0,0.08);
font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;
font-size: 14px !important;
color: #333 !important;
overflow: hidden;
display: none;
flex-direction: column;
animation: fs-slide-in 0.25s ease;
}
#fs-panel.fs-show { display: flex; }
@keyframes fs-slide-in {
from { opacity: 0; transform: translateY(-12px) scale(0.96); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
/* 面板头部 */
#fs-panel .fs-header {
padding: 16px 18px 12px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
}
#fs-panel .fs-header-left {
display: flex;
flex-direction: column;
gap: 2px;
}
#fs-panel .fs-header-title {
font-size: 15px;
font-weight: 600;
letter-spacing: 0.5px;
}
#fs-panel .fs-header-host {
font-size: 10px;
opacity: 0.7;
font-weight: 400;
}
#fs-panel .fs-header-actions {
display: flex;
align-items: center;
gap: 6px;
}
#fs-panel .fs-header-gear,
#fs-panel .fs-header-close {
width: 28px; height: 28px;
border-radius: 50%;
border: none;
background: rgba(255,255,255,0.2);
color: #fff;
font-size: 16px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.15s;
line-height: 1;
}
#fs-panel .fs-header-gear:hover,
#fs-panel .fs-header-close:hover { background: rgba(255,255,255,0.35); }
#fs-panel .fs-header-gear.fs-gear-active { background: rgba(255,255,255,0.45); }
/* 开关 */
#fs-panel .fs-toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 18px;
background: #f8f8ff;
border-bottom: 1px solid #eee;
flex-shrink: 0;
}
#fs-panel .fs-toggle-label { font-size: 13px; color: #666; }
#fs-panel .fs-toggle-switch { position: relative; width: 44px; height: 24px; cursor: pointer; }
#fs-panel .fs-toggle-switch input { opacity: 0; width: 0; height: 0; }
#fs-panel .fs-toggle-slider {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
background: #ccc;
border-radius: 24px;
transition: background 0.25s;
}
#fs-panel .fs-toggle-slider::before {
content: '';
position: absolute;
width: 18px; height: 18px;
left: 3px; bottom: 3px;
background: #fff;
border-radius: 50%;
transition: transform 0.25s;
}
#fs-panel .fs-toggle-switch input:checked + .fs-toggle-slider { background: #667eea; }
#fs-panel .fs-toggle-switch input:checked + .fs-toggle-slider::before { transform: translateX(20px); }
/* 字体列表 */
#fs-panel .fs-list-container {
flex: 1;
overflow-y: auto;
padding: 4px 0;
scrollbar-width: thin;
scrollbar-color: #d0d0d0 transparent;
}
#fs-panel .fs-list-container::-webkit-scrollbar { width: 5px; }
#fs-panel .fs-list-container::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }
/* 分组标题 */
#fs-panel .fs-group-title {
padding: 8px 18px 4px;
font-size: 11px;
font-weight: 600;
color: #999;
text-transform: uppercase;
letter-spacing: 1px;
user-select: none;
}
/* 字体项 */
#fs-panel .fs-font-item {
display: flex;
align-items: center;
padding: 7px 12px 7px 18px;
cursor: pointer;
transition: background 0.12s;
gap: 8px;
}
#fs-panel .fs-font-item:hover { background: #f0f0ff; }
#fs-panel .fs-font-item.fs-active { background: #eef0ff; }
#fs-panel .fs-font-item .fs-radio {
width: 16px; height: 16px;
border-radius: 50%;
border: 2px solid #ccc;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
transition: border-color 0.15s;
}
#fs-panel .fs-font-item.fs-active .fs-radio { border-color: #667eea; }
#fs-panel .fs-font-item.fs-active .fs-radio::after {
content: '';
width: 8px; height: 8px;
border-radius: 50%;
background: #667eea;
}
#fs-panel .fs-font-item .fs-font-info {
flex: 1;
min-width: 0;
}
#fs-panel .fs-font-item .fs-font-name {
font-size: 13px;
color: #333;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
#fs-panel .fs-font-item .fs-font-preview {
font-size: 12px;
color: #888;
margin-top: 1px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
#fs-panel .fs-font-item .fs-has-settings {
font-size: 9px;
color: #667eea;
margin-left: 4px;
font-weight: 600;
}
/* 设置齿轮按钮(字体项) */
#fs-panel .fs-font-item .fs-settings-btn {
width: 22px; height: 22px;
border-radius: 4px;
border: none;
background: transparent;
color: #bbb;
font-size: 13px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.15s;
flex-shrink: 0;
opacity: 0;
}
#fs-panel .fs-font-item:hover .fs-settings-btn { opacity: 1; }
#fs-panel .fs-font-item .fs-settings-btn:hover { background: #e8e8ff; color: #667eea; }
#fs-panel .fs-font-item .fs-settings-btn.fs-settings-active { opacity: 1; color: #667eea; }
/* 删除按钮 */
#fs-panel .fs-font-item .fs-delete-btn {
width: 22px; height: 22px;
border-radius: 4px;
border: none;
background: transparent;
color: #bbb;
font-size: 14px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.15s;
flex-shrink: 0;
opacity: 0;
}
#fs-panel .fs-font-item:hover .fs-delete-btn { opacity: 1; }
#fs-panel .fs-font-item .fs-delete-btn:hover { background: #ffe0e0; color: #e55; }
/* 字体设置面板 */
#fs-panel .fs-font-settings {
background: #f5f5ff;
border-bottom: 1px solid #e0e0ee;
padding: 10px 18px;
display: none;
}
#fs-panel .fs-font-settings.fs-show { display: block; }
#fs-panel .fs-font-settings .fs-settings-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
}
#fs-panel .fs-font-settings .fs-settings-row:last-child { margin-bottom: 0; }
#fs-panel .fs-font-settings .fs-settings-label {
font-size: 11px;
color: #777;
width: 42px;
flex-shrink: 0;
}
#fs-panel .fs-font-settings .fs-settings-input {
flex: 1;
height: 28px;
border: 1px solid #d8d8e8;
border-radius: 6px;
padding: 0 8px;
font-size: 12px;
font-family: inherit;
outline: none;
background: #fff;
color: #333;
transition: border-color 0.15s;
}
#fs-panel .fs-font-settings .fs-settings-input:focus { border-color: #667eea; }
#fs-panel .fs-font-settings .fs-settings-select {
flex: 1;
height: 28px;
border: 1px solid #d8d8e8;
border-radius: 6px;
padding: 0 6px;
font-size: 12px;
font-family: inherit;
outline: none;
background: #fff;
color: #333;
cursor: pointer;
}
#fs-panel .fs-font-settings .fs-settings-hint {
font-size: 10px;
color: #aaa;
margin-top: 4px;
}
/* ========== 设置视图 ========== */
#fs-panel .fs-settings-view {
flex: 1;
overflow-y: auto;
padding: 0;
scrollbar-width: thin;
scrollbar-color: #d0d0d0 transparent;
}
#fs-panel .fs-settings-view::-webkit-scrollbar { width: 5px; }
#fs-panel .fs-settings-view::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }
#fs-panel .fs-sv-section {
padding: 12px 18px;
border-bottom: 1px solid #f0f0f0;
}
#fs-panel .fs-sv-section:last-child { border-bottom: none; }
#fs-panel .fs-sv-section-title {
font-size: 12px;
font-weight: 600;
color: #888;
margin-bottom: 10px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
#fs-panel .fs-sv-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 0;
min-height: 32px;
}
#fs-panel .fs-sv-row-label {
font-size: 13px;
color: #444;
flex-shrink: 0;
}
#fs-panel .fs-sv-row-label small {
display: block;
font-size: 10px;
color: #aaa;
font-weight: 400;
margin-top: 1px;
}
#fs-panel .fs-sv-row-right {
display: flex;
align-items: center;
gap: 6px;
}
/* 设置页的 select */
#fs-panel .fs-sv-select {
height: 30px;
border: 1px solid #d8d8e8;
border-radius: 6px;
padding: 0 8px;
font-size: 12px;
font-family: inherit;
outline: none;
background: #fff;
color: #333;
cursor: pointer;
min-width: 100px;
}
#fs-panel .fs-sv-select:focus { border-color: #667eea; }
/* ========== 按钮大小滑块 ========== */
#fs-panel .fs-sv-range-wrapper {
display: flex;
align-items: center;
gap: 10px;
}
#fs-panel .fs-sv-range {
-webkit-appearance: none;
appearance: none;
width: 110px;
height: 6px;
border-radius: 3px;
background: linear-gradient(to right, #667eea 0%, #667eea var(--range-pct, 50%), #ddd var(--range-pct, 50%), #ddd 100%);
outline: none;
cursor: pointer;
transition: background 0.1s;
}
#fs-panel .fs-sv-range::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 18px;
height: 18px;
border-radius: 50%;
background: #fff;
border: 3px solid #667eea;
cursor: pointer;
box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);
transition: transform 0.15s, box-shadow 0.15s;
}
#fs-panel .fs-sv-range::-webkit-slider-thumb:hover {
transform: scale(1.15);
box-shadow: 0 2px 8px rgba(102, 126, 234, 0.5);
}
#fs-panel .fs-sv-range::-moz-range-thumb {
width: 18px;
height: 18px;
border-radius: 50%;
background: #fff;
border: 3px solid #667eea;
cursor: pointer;
box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);
}
#fs-panel .fs-sv-range::-moz-range-track {
height: 6px;
border-radius: 3px;
background: #ddd;
}
#fs-panel .fs-sv-range::-moz-range-progress {
height: 6px;
border-radius: 3px;
background: #667eea;
}
#fs-panel .fs-sv-range-value {
font-size: 12px;
color: #667eea;
font-weight: 700;
min-width: 38px;
text-align: right;
font-variant-numeric: tabular-nums;
}
/* 按钮大小预览小圆点 */
#fs-panel .fs-sv-btn-preview {
border-radius: 50%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);
transition: width 0.2s ease, height 0.2s ease;
flex-shrink: 0;
}
/* 设置页的开关(复用 toggle 样式) */
#fs-panel .fs-sv-toggle { position: relative; width: 44px; height: 24px; cursor: pointer; }
#fs-panel .fs-sv-toggle input { opacity: 0; width: 0; height: 0; }
#fs-panel .fs-sv-toggle-slider {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
background: #ccc;
border-radius: 24px;
transition: background 0.25s;
}
#fs-panel .fs-sv-toggle-slider::before {
content: '';
position: absolute;
width: 18px; height: 18px;
left: 3px; bottom: 3px;
background: #fff;
border-radius: 50%;
transition: transform 0.25s;
}
#fs-panel .fs-sv-toggle input:checked + .fs-sv-toggle-slider { background: #667eea; }
#fs-panel .fs-sv-toggle input:checked + .fs-sv-toggle-slider::before { transform: translateX(20px); }
/* 设置页按钮 */
#fs-panel .fs-sv-btn {
height: 32px;
border: 1px solid #d8d8e8;
border-radius: 8px;
padding: 0 14px;
font-size: 12px;
font-family: inherit;
cursor: pointer;
background: #fff;
color: #555;
transition: all 0.15s;
}
#fs-panel .fs-sv-btn:hover { border-color: #667eea; color: #667eea; background: #f5f5ff; }
#fs-panel .fs-sv-btn-danger { color: #e55; }
#fs-panel .fs-sv-btn-danger:hover { border-color: #e55; color: #e55; background: #fff5f5; }
/* 上传字体区域(设置页内) */
#fs-panel .fs-sv-upload-btn {
flex: 1;
height: 36px;
border: 1.5px dashed #bbb;
border-radius: 8px;
background: #fff;
color: #667eea;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: border-color 0.15s, background 0.15s;
white-space: nowrap;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
}
#fs-panel .fs-sv-upload-btn:hover {
border-color: #667eea;
background: #f0f0ff;
}
#fs-panel .fs-sv-upload-hint {
font-size: 10px;
color: #aaa;
margin-top: 6px;
}
/* Toast - 屏幕顶部居中 */
#fs-toast {
position: fixed;
z-index: 2147483647;
padding: 10px 24px;
border-radius: 10px;
font-size: 13px;
font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;
color: #fff;
pointer-events: none;
display: none;
left: 50%;
transform: translateX(-50%);
top: 24px;
white-space: nowrap;
}
#fs-toast.fs-toast-show { display: block; }
#fs-toast.fs-toast-success { background: #4caf50; }
#fs-toast.fs-toast-error { background: #f44336; }
#fs-toast.fs-toast-info { background: #667eea; }
`;
}
let mainStyleEl = null;
function injectStyles() {
if (mainStyleEl) mainStyleEl.remove();
if (typeof GM_addStyle === 'function') {
// GM_addStyle 无法更新,用 style 标签替代
mainStyleEl = document.createElement('style');
mainStyleEl.id = 'fs-main-styles';
mainStyleEl.textContent = buildStyles();
document.head.appendChild(mainStyleEl);
} else {
mainStyleEl = document.createElement('style');
mainStyleEl.id = 'fs-main-styles';
mainStyleEl.textContent = buildStyles();
document.head.appendChild(mainStyleEl);
}
}
function updateStyles() {
if (mainStyleEl) {
mainStyleEl.textContent = buildStyles();
}
// 更新按钮实际尺寸
triggerBtn.style.width = BTN_SIZE + 'px';
triggerBtn.style.height = BTN_SIZE + 'px';
}
injectStyles();
previewStyleEl = document.createElement('style');
previewStyleEl.id = 'fs-preview-styles';
document.head.appendChild(previewStyleEl);
const uiRecoveryStyleEl = document.createElement('style');
uiRecoveryStyleEl.id = 'fs-ui-recovery';
uiRecoveryStyleEl.textContent = `
#fs-trigger-btn, #fs-trigger-btn *,
#fs-overlay,
#fs-panel, #fs-panel *,
#fs-toast, #fs-toast * {
font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;
}
`;
document.head.appendChild(uiRecoveryStyleEl);
// ==================== DOM 构建 ====================
const triggerBtn = document.createElement('button');
triggerBtn.id = 'fs-trigger-btn';
triggerBtn.title = '字体更换器(可拖拽移动)';
triggerBtn.innerHTML = '<span class="fs-btn-icon">Aa</span>';
triggerBtn.classList.add('fs-side-' + btnSide, 'fs-entering');
document.body.appendChild(triggerBtn);
const overlay = document.createElement('div');
overlay.id = 'fs-overlay';
document.body.appendChild(overlay);
const panel = document.createElement('div');
panel.id = 'fs-panel';
panel.innerHTML = `
<div class="fs-header">
<div class="fs-header-left">
<span class="fs-header-title">字体更换器</span>
<span class="fs-header-host">${CURRENT_HOST}</span>
</div>
<div class="fs-header-actions">
<button class="fs-header-gear" id="fs-header-gear-btn" title="设置">⚙</button>
<button class="fs-header-close" title="关闭">×</button>
</div>
</div>
<div class="fs-toggle-row">
<span class="fs-toggle-label">启用字体替换(仅当前站点)</span>
<label class="fs-toggle-switch">
<input type="checkbox" id="fs-enabled-toggle">
<span class="fs-toggle-slider"></span>
</label>
</div>
<!-- 字体列表视图 -->
<div class="fs-list-container" id="fs-font-list"></div>
<!-- 设置视图 -->
<div class="fs-settings-view" id="fs-settings-view" style="display:none;"></div>
`;
document.body.appendChild(panel);
const toast = document.createElement('div');
toast.id = 'fs-toast';
document.body.appendChild(toast);
// 隐藏的文件 input(全局共用)
const fontFileInput = document.createElement('input');
fontFileInput.type = 'file';
fontFileInput.id = 'fs-font-file-input';
fontFileInput.accept = '.woff2,.woff,.ttf,.otf,.eot';
fontFileInput.multiple = true;
fontFileInput.style.display = 'none';
document.body.appendChild(fontFileInput);
// ==================== 按钮位置管理 ====================
function applyBtnPosition() {
triggerBtn.style.top = btnY + 'px';
triggerBtn.style.left = '';
triggerBtn.style.right = '';
triggerBtn.classList.remove('fs-side-left', 'fs-side-right');
triggerBtn.classList.add('fs-side-' + btnSide);
if (!btnCollapsed) triggerBtn.style.transform = '';
}
function clampBtnY() {
btnY = Math.max(0, Math.min(btnY, window.innerHeight - BTN_SIZE));
}
// ==================== 收缩 / 展开 ====================
function collapseBtn() {
if (btnCollapsed || panelVisible) return;
if (!globalSettings.autoCollapse) return;
btnCollapsed = true;
triggerBtn.classList.add('fs-collapsed');
}
function expandBtn() {
if (!btnCollapsed) return;
btnCollapsed = false;
triggerBtn.classList.remove('fs-collapsed');
resetIdleTimer();
}
function resetIdleTimer() {
if (idleTimer) clearTimeout(idleTimer);
if (!panelVisible && globalSettings.autoCollapse) {
idleTimer = setTimeout(collapseBtn, IDLE_MS);
}
}
document.addEventListener('mousemove', (e) => {
if (!btnCollapsed) return;
const vx = window.innerWidth;
const nearEdge = (btnSide === 'right' && e.clientX > vx - HOVER_ZONE) ||
(btnSide === 'left' && e.clientX < HOVER_ZONE);
const nearBtnY = e.clientY >= btnY - HOVER_ZONE &&
e.clientY <= btnY + BTN_SIZE + HOVER_ZONE;
if (nearEdge && nearBtnY) {
expandBtn();
}
});
triggerBtn.addEventListener('mouseenter', () => {
if (!btnCollapsed) resetIdleTimer();
});
// ==================== 拖拽逻辑 ====================
function onPointerDown(e) {
if (btnCollapsed) return;
if (e.button && e.button !== 0) return;
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
isDragging = true;
hasDragged = false;
dragStartX = clientX;
dragStartY = clientY;
const rect = triggerBtn.getBoundingClientRect();
btnStartLeft = rect.left;
btnStartTop = rect.top;
e.preventDefault();
}
function onPointerMove(e) {
if (!isDragging) return;
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
const dx = clientX - dragStartX;
const dy = clientY - dragStartY;
if (!hasDragged && Math.abs(dx) < DRAG_THRESHOLD && Math.abs(dy) < DRAG_THRESHOLD) return;
if (!hasDragged) { hasDragged = true; closePanel(); }
triggerBtn.style.right = 'auto';
triggerBtn.style.left = (btnStartLeft + dx) + 'px';
triggerBtn.style.top = (btnStartTop + dy) + 'px';
triggerBtn.classList.remove('fs-collapsed');
triggerBtn.classList.add('fs-dragging');
btnCollapsed = false;
e.preventDefault();
}
function onPointerUp(e) {
if (!isDragging) return;
isDragging = false;
triggerBtn.classList.remove('fs-dragging');
if (hasDragged) {
const rect = triggerBtn.getBoundingClientRect();
btnSide = (rect.left + rect.width / 2) < window.innerWidth / 2 ? 'left' : 'right';
btnY = rect.top;
clampBtnY();
saveBtnPosition();
applyBtnPosition();
resetIdleTimer();
setTimeout(() => { hasDragged = false; }, 50);
}
}
triggerBtn.addEventListener('mousedown', onPointerDown);
document.addEventListener('mousemove', onPointerMove);
document.addEventListener('mouseup', onPointerUp);
triggerBtn.addEventListener('touchstart', onPointerDown, { passive: false });
document.addEventListener('touchmove', onPointerMove, { passive: false });
document.addEventListener('touchend', onPointerUp);
triggerBtn.addEventListener('click', (e) => {
if (hasDragged || btnCollapsed) return;
togglePanel();
});
window.addEventListener('resize', () => {
clampBtnY();
applyBtnPosition();
if (panelVisible) positionPanel();
});
// ==================== 面板定位 ====================
function positionPanel() {
const btnRect = triggerBtn.getBoundingClientRect();
const vw = window.innerWidth;
const vh = window.innerHeight;
const gap = 10;
const inwardOffset = BTN_SIZE + 12;
let left, top;
if (btnSide === 'right') {
left = btnRect.left - PANEL_W - gap;
if (left < MARGIN) {
left = btnRect.right - PANEL_W + inwardOffset;
}
} else {
left = btnRect.right + gap;
if (left + PANEL_W > vw - MARGIN) {
left = btnRect.left - inwardOffset;
}
}
left = Math.max(MARGIN, Math.min(left, vw - PANEL_W - MARGIN));
top = btnRect.top;
if (top + PANEL_MAX_H > vh - MARGIN) top = vh - PANEL_MAX_H - MARGIN;
if (top < MARGIN) top = MARGIN;
panel.style.left = left + 'px';
panel.style.top = top + 'px';
}
// ==================== 字体应用(核心) ====================
let injectedStyleEl = null;
function applyFont(fontValue) {
if (injectedStyleEl) {
injectedStyleEl.remove();
injectedStyleEl = null;
}
if (!fontValue || !isEnabled) return;
const settings = getFontSettings(fontValue);
const fontSize = (settings && settings.size) ? settings.size : '';
const fontWeight = (settings && settings.weight) ? settings.weight : '';
let extraProps = '';
if (fontSize) extraProps += `font-size: ${fontSize} !important;\n`;
if (fontWeight) extraProps += `font-weight: ${fontWeight} !important;\n`;
const excludeInputs = globalSettings.excludeInputs;
const inputSelector = excludeInputs ? '' : `, input, textarea, select, button`;
injectedStyleEl = document.createElement('style');
injectedStyleEl.id = 'fs-injected-font';
injectedStyleEl.textContent = `
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video${inputSelector} {
font-family: ${fontValue} !important;
${extraProps}
}
`;
document.head.appendChild(injectedStyleEl);
}
function loadCustomFontFace(name, url, format) {
const id = 'fs-fontface-' + CSS.escape(name.replace(/\s+/g, '-'));
if (document.getElementById(id)) return;
const styleEl = document.createElement('style');
styleEl.id = id;
const srcStr = format
? `url("${url}") format("${format}")`
: `url("${url}")`;
styleEl.textContent = `@font-face { font-family: "${name}"; src: ${srcStr}; }`;
document.head.appendChild(styleEl);
}
// ==================== 预览样式更新 ====================
function updatePreviewStyles() {
const allFonts = [...PRESET_FONTS, ...customFonts];
let css = '';
allFonts.forEach((font, i) => {
if (font.value) {
css += `#fs-panel #fs-preview-${i} { font-family: ${font.value} !important; }\n`;
}
});
previewStyleEl.textContent = css;
}
// ==================== 渲染字体列表 ====================
function renderFontList() {
const listContainer = document.getElementById('fs-font-list');
listContainer.innerHTML = '';
let idx = 0;
const presetGroup = document.createElement('div');
presetGroup.className = 'fs-group-title';
presetGroup.textContent = '预置字体';
listContainer.appendChild(presetGroup);
PRESET_FONTS.forEach(font => {
presetGroup.appendChild(createFontItem(font, false, idx++));
});
if (customFonts.length > 0) {
const customGroup = document.createElement('div');
customGroup.className = 'fs-group-title';
customGroup.textContent = '自定义字体(全局)';
listContainer.appendChild(customGroup);
customFonts.forEach(font => {
customGroup.appendChild(createFontItem(font, true, idx++));
});
}
updatePreviewStyles();
}
function createFontItem(font, isCustom, index) {
const isActive = activeFontValue === font.value;
const wrapper = document.createElement('div');
const item = document.createElement('div');
item.className = 'fs-font-item' + (isActive ? ' fs-active' : '');
const radio = document.createElement('div');
radio.className = 'fs-radio';
const info = document.createElement('div');
info.className = 'fs-font-info';
const nameEl = document.createElement('div');
nameEl.className = 'fs-font-name';
nameEl.textContent = font.name;
const settings = getFontSettings(font.value);
if (settings && (settings.size || settings.weight) && font.value) {
const badge = document.createElement('span');
badge.className = 'fs-has-settings';
let label = '';
if (settings.size) label += settings.size;
if (settings.weight && settings.weight !== 'normal') label += (label ? ' ' : '') + 'B';
badge.textContent = label ? `[${label}]` : '';
nameEl.appendChild(badge);
}
const preview = document.createElement('div');
preview.className = 'fs-font-preview';
preview.id = 'fs-preview-' + index;
preview.textContent = '你好世界 Hello World 0123';
info.appendChild(nameEl);
info.appendChild(preview);
item.appendChild(radio);
item.appendChild(info);
if (font.value) {
const settingsBtn = document.createElement('button');
settingsBtn.className = 'fs-settings-btn' + (expandedSettingsSet.has(font.value) ? ' fs-settings-active' : '');
settingsBtn.innerHTML = '⚙';
settingsBtn.title = '字号/加粗设置';
settingsBtn.addEventListener('click', (e) => {
e.stopPropagation();
toggleSettings(font.value, wrapper);
});
item.appendChild(settingsBtn);
}
if (isCustom) {
const delBtn = document.createElement('button');
delBtn.className = 'fs-delete-btn';
delBtn.innerHTML = '×';
delBtn.title = '删除此字体';
delBtn.addEventListener('click', (e) => {
e.stopPropagation();
deleteCustomFont(font);
});
item.appendChild(delBtn);
}
item.addEventListener('click', () => selectFont(font));
wrapper.appendChild(item);
if (font.value) {
const settingsPanel = document.createElement('div');
settingsPanel.className = 'fs-font-settings' + (expandedSettingsSet.has(font.value) ? ' fs-show' : '');
settingsPanel.id = 'fs-settings-' + index;
const current = getFontSettings(font.value) || {};
settingsPanel.innerHTML = `
<div class="fs-settings-row">
<span class="fs-settings-label">字号</span>
<input class="fs-settings-input" type="text"
data-font-value="${font.value.replace(/"/g, '"')}"
data-field="size"
placeholder="如 16px, 1.2em, 120%"
value="${current.size || ''}" />
</div>
<div class="fs-settings-row">
<span class="fs-settings-label">加粗</span>
<select class="fs-settings-select"
data-font-value="${font.value.replace(/"/g, '"')}"
data-field="weight">
<option value="">默认</option>
<option value="100">100 - 极细</option>
<option value="200">200 - 特细</option>
<option value="300">300 - 细体</option>
<option value="normal">400 - 常规</option>
<option value="500">500 - 中等</option>
<option value="600">600 - 半粗</option>
<option value="bold">700 - 粗体</option>
<option value="800">800 - 特粗</option>
<option value="900">900 - 极粗</option>
</select>
</div>
<div class="fs-settings-hint">设置仅对当前站点生效,留空则不覆盖</div>
`;
const selectEl = settingsPanel.querySelector('select');
if (current.weight) selectEl.value = current.weight;
settingsPanel.querySelectorAll('.fs-settings-input, .fs-settings-select').forEach(input => {
const handler = () => {
const fv = input.dataset.fontValue;
const field = input.dataset.field;
const val = input.value.trim();
const s = getFontSettings(fv) || {};
if (val) {
s[field] = val;
} else {
delete s[field];
}
if (Object.keys(s).length === 0) {
removeFontSettings(fv);
} else {
setFontSettings(fv, s);
}
if (fv === activeFontValue) {
applyFont(activeFontValue);
}
const settingsPanelEl = input.closest('.fs-font-settings');
if (hasNonDefaultSettings(fv)) {
expandedSettingsSet.add(fv);
if (settingsPanelEl) settingsPanelEl.classList.add('fs-show');
} else {
expandedSettingsSet.delete(fv);
if (settingsPanelEl) settingsPanelEl.classList.remove('fs-show');
}
const wrapperEl = settingsPanelEl ? settingsPanelEl.previousElementSibling : null;
if (wrapperEl) {
const gearBtn = wrapperEl.querySelector('.fs-settings-btn');
if (gearBtn) {
if (expandedSettingsSet.has(fv)) gearBtn.classList.add('fs-settings-active');
else gearBtn.classList.remove('fs-settings-active');
}
}
};
input.addEventListener('input', handler);
input.addEventListener('change', handler);
});
wrapper.appendChild(settingsPanel);
}
return wrapper;
}
function toggleSettings(fontValue, wrapper) {
if (expandedSettingsSet.has(fontValue)) {
expandedSettingsSet.delete(fontValue);
} else {
expandedSettingsSet.add(fontValue);
}
renderFontList();
}
// ==================== 字体选择 ====================
function selectFont(font) {
activeFontValue = font.value;
saveToStorage(STORAGE_KEY_ACTIVE_FONT, activeFontValue);
if (font.value && isEnabled) {
applyFont(font.value);
} else {
applyFont('');
}
renderFontList();
showToast(`已切换为:${font.name}`, 'success');
}
function deleteCustomFont(font) {
customFonts = customFonts.filter(f => f.value !== font.value);
saveToStorage(STORAGE_KEY_CUSTOM_FONTS, customFonts);
removeFontSettings(font.value);
if (activeFontValue === font.value) {
activeFontValue = '';
saveToStorage(STORAGE_KEY_ACTIVE_FONT, activeFontValue);
applyFont('');
}
const faceId = 'fs-fontface-' + CSS.escape(font.name.replace(/\s+/g, '-'));
const faceEl = document.getElementById(faceId);
if (faceEl) faceEl.remove();
renderFontList();
showToast(`已删除:${font.name}`, 'info');
}
// ==================== 添加自定义字体 ====================
function addUploadedFont(name, dataUrl, format) {
const value = `"${name}", sans-serif`;
if (customFonts.some(f => f.name === name)) {
showToast('该字体名称已存在', 'error');
return;
}
loadCustomFontFace(name, dataUrl, format);
customFonts.push({ name, value, dataUrl, format });
saveToStorage(STORAGE_KEY_CUSTOM_FONTS, customFonts);
renderFontList();
showToast(`已添加字体:${name}`, 'success');
}
function handleFontFileUpload(files) {
if (!files || files.length === 0) return;
const validExts = ['.woff2', '.woff', '.ttf', '.otf', '.eot'];
const formatMap = {
'woff2': 'woff2',
'woff': 'woff',
'ttf': 'truetype',
'otf': 'opentype',
'eot': 'embedded-opentype',
};
Array.from(files).forEach(file => {
const ext = '.' + file.name.split('.').pop().toLowerCase();
if (!validExts.includes(ext)) {
showToast(`不支持的格式:${file.name}`, 'error');
return;
}
const fontName = file.name.replace(/\.[^.]+$/, '');
const format = formatMap[ext.replace('.', '')] || 'truetype';
if (customFonts.some(f => f.name === fontName)) {
showToast(`字体已存在:${fontName}`, 'error');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
const dataUrl = e.target.result;
addUploadedFont(fontName, dataUrl, format);
};
reader.onerror = function() {
showToast(`读取失败:${file.name}`, 'error');
};
reader.readAsDataURL(file);
});
}
function reloadCustomFonts() {
customFonts.forEach(font => {
const url = font.dataUrl || font.url;
if (url) loadCustomFontFace(font.name, url, font.format || null);
});
}
// ==================== 滑块进度更新工具 ====================
function updateRangeProgress(rangeEl) {
const min = parseFloat(rangeEl.min) || 0;
const max = parseFloat(rangeEl.max) || 100;
const val = parseFloat(rangeEl.value) || min;
const pct = ((val - min) / (max - min)) * 100;
rangeEl.style.setProperty('--range-pct', pct + '%');
}
// ==================== 设置视图渲染 ====================
function renderSettingsView() {
const view = document.getElementById('fs-settings-view');
view.innerHTML = '';
// --- 外观 ---
const secAppearance = document.createElement('div');
secAppearance.className = 'fs-sv-section';
secAppearance.innerHTML = `<div class="fs-sv-section-title">外观</div>`;
// 按钮大小(滑块 + 预览)
const rowBtnSize = document.createElement('div');
rowBtnSize.className = 'fs-sv-row';
const btnPreviewSize = Math.max(12, Math.round(BTN_SIZE * 0.42));
rowBtnSize.innerHTML = `
<span class="fs-sv-row-label">按钮大小<small>拖动滑块调整悬浮按钮尺寸</small></span>
<div class="fs-sv-row-right">
<div class="fs-sv-btn-preview" id="fs-sv-btnPreview" style="width:${btnPreviewSize}px;height:${btnPreviewSize}px;"></div>
<div class="fs-sv-range-wrapper">
<input type="range" class="fs-sv-range" id="fs-sv-btnSize"
min="28" max="60" step="2" value="${BTN_SIZE}">
<span class="fs-sv-range-value" id="fs-sv-btnSize-val">${BTN_SIZE}px</span>
</div>
</div>
`;
secAppearance.appendChild(rowBtnSize);
// 排除输入框
const rowExcludeInputs = document.createElement('div');
rowExcludeInputs.className = 'fs-sv-row';
rowExcludeInputs.innerHTML = `
<span class="fs-sv-row-label">排除输入框<small>不对 input / textarea / select 应用字体</small></span>
<div class="fs-sv-row-right">
<label class="fs-sv-toggle">
<input type="checkbox" id="fs-sv-excludeInputs" ${globalSettings.excludeInputs ? 'checked' : ''}>
<span class="fs-sv-toggle-slider"></span>
</label>
</div>
`;
secAppearance.appendChild(rowExcludeInputs);
view.appendChild(secAppearance);
// --- 行为 ---
const secBehavior = document.createElement('div');
secBehavior.className = 'fs-sv-section';
secBehavior.innerHTML = `<div class="fs-sv-section-title">行为</div>`;
// 自动吸附收起
const rowAutoCollapse = document.createElement('div');
rowAutoCollapse.className = 'fs-sv-row';
rowAutoCollapse.innerHTML = `
<span class="fs-sv-row-label">自动吸附收起<small>闲置后按钮收缩至屏幕边缘</small></span>
<div class="fs-sv-row-right">
<label class="fs-sv-toggle">
<input type="checkbox" id="fs-sv-autoCollapse" ${globalSettings.autoCollapse ? 'checked' : ''}>
<span class="fs-sv-toggle-slider"></span>
</label>
</div>
`;
secBehavior.appendChild(rowAutoCollapse);
// 收起延迟
const rowIdleMs = document.createElement('div');
rowIdleMs.className = 'fs-sv-row';
rowIdleMs.innerHTML = `
<span class="fs-sv-row-label">收起延迟<small>闲置多久后自动收起</small></span>
<div class="fs-sv-row-right">
<select class="fs-sv-select" id="fs-sv-idleMs">
<option value="3000" ${globalSettings.idleMs === 3000 ? 'selected' : ''}>3 秒</option>
<option value="5000" ${globalSettings.idleMs === 5000 ? 'selected' : ''}>5 秒</option>
<option value="10000" ${globalSettings.idleMs === 10000 ? 'selected' : ''}>10 秒</option>
<option value="15000" ${globalSettings.idleMs === 15000 ? 'selected' : ''}>15 秒</option>
<option value="30000" ${globalSettings.idleMs === 30000 ? 'selected' : ''}>30 秒</option>
</select>
</div>
`;
secBehavior.appendChild(rowIdleMs);
// Toast 时长
const rowToast = document.createElement('div');
rowToast.className = 'fs-sv-row';
rowToast.innerHTML = `
<span class="fs-sv-row-label">提示显示时长<small>操作反馈提示的持续时间</small></span>
<div class="fs-sv-row-right">
<select class="fs-sv-select" id="fs-sv-toastDuration">
<option value="1000" ${globalSettings.toastDuration === 1000 ? 'selected' : ''}>1 秒</option>
<option value="2000" ${globalSettings.toastDuration === 2000 ? 'selected' : ''}>2 秒</option>
<option value="3000" ${globalSettings.toastDuration === 3000 ? 'selected' : ''}>3 秒</option>
</select>
</div>
`;
secBehavior.appendChild(rowToast);
view.appendChild(secBehavior);
// --- 字体管理 ---
const secFonts = document.createElement('div');
secFonts.className = 'fs-sv-section';
secFonts.innerHTML = `<div class="fs-sv-section-title">字体管理</div>`;
const rowUpload = document.createElement('div');
rowUpload.style.cssText = 'padding: 4px 0;';
rowUpload.innerHTML = `
<button class="fs-sv-upload-btn" id="fs-sv-upload-btn">📂 选择字体文件</button>
<div class="fs-sv-upload-hint">支持 .woff2 / .woff / .ttf / .otf 格式,全局共享</div>
`;
secFonts.appendChild(rowUpload);
// 已导入字体数量
if (customFonts.length > 0) {
const rowFontCount = document.createElement('div');
rowFontCount.className = 'fs-sv-row';
rowFontCount.innerHTML = `
<span class="fs-sv-row-label">已导入 ${customFonts.length} 个自定义字体</span>
<div class="fs-sv-row-right">
<button class="fs-sv-btn fs-sv-btn-danger" id="fs-sv-clearFonts">全部清除</button>
</div>
`;
secFonts.appendChild(rowFontCount);
}
view.appendChild(secFonts);
// --- 数据 ---
const secData = document.createElement('div');
secData.className = 'fs-sv-section';
secData.innerHTML = `<div class="fs-sv-section-title">数据</div>`;
const rowResetPos = document.createElement('div');
rowResetPos.className = 'fs-sv-row';
rowResetPos.innerHTML = `
<span class="fs-sv-row-label">重置按钮位置<small>将悬浮按钮恢复到默认位置</small></span>
<div class="fs-sv-row-right">
<button class="fs-sv-btn" id="fs-sv-resetPos">重置</button>
</div>
`;
secData.appendChild(rowResetPos);
const rowResetSite = document.createElement('div');
rowResetSite.className = 'fs-sv-row';
rowResetSite.innerHTML = `
<span class="fs-sv-row-label">重置当前站点设置<small>清除本站的字体选择和字号等设置</small></span>
<div class="fs-sv-row-right">
<button class="fs-sv-btn fs-sv-btn-danger" id="fs-sv-resetSite">重置</button>
</div>
`;
secData.appendChild(rowResetSite);
view.appendChild(secData);
// ========== 绑定设置事件 ==========
// 按钮大小 — 滑块实时拖动预览
const btnSizeRange = document.getElementById('fs-sv-btnSize');
const btnSizeVal = document.getElementById('fs-sv-btnSize-val');
const btnPreview = document.getElementById('fs-sv-btnPreview');
// 初始化滑块进度
updateRangeProgress(btnSizeRange);
btnSizeRange.addEventListener('input', function() {
const val = parseInt(this.value);
btnSizeVal.textContent = val + 'px';
// 更新滑块进度条颜色
updateRangeProgress(this);
// 更新预览小圆点
const previewPx = Math.max(12, Math.round(val * 0.42));
btnPreview.style.width = previewPx + 'px';
btnPreview.style.height = previewPx + 'px';
// 实时更新实际按钮大小
globalSettings.btnSize = val;
saveGlobalSettings();
refreshDerivedSettings();
updateStyles();
clampBtnY();
applyBtnPosition();
});
btnSizeRange.addEventListener('change', function() {
showToast(`按钮大小已更新为 ${this.value}px`, 'info');
});
// 排除输入框
document.getElementById('fs-sv-excludeInputs').addEventListener('change', function() {
globalSettings.excludeInputs = this.checked;
saveGlobalSettings();
if (activeFontValue && isEnabled) applyFont(activeFontValue);
showToast(this.checked ? '已排除输入框' : '输入框将应用字体', 'info');
});
// 自动吸附收起
document.getElementById('fs-sv-autoCollapse').addEventListener('change', function() {
globalSettings.autoCollapse = this.checked;
saveGlobalSettings();
refreshDerivedSettings();
if (this.checked) {
resetIdleTimer();
} else {
if (idleTimer) clearTimeout(idleTimer);
if (btnCollapsed) expandBtn();
}
showToast(this.checked ? '已开启自动收起' : '已关闭自动收起', 'info');
});
// 收起延迟
document.getElementById('fs-sv-idleMs').addEventListener('change', function() {
globalSettings.idleMs = parseInt(this.value);
saveGlobalSettings();
refreshDerivedSettings();
resetIdleTimer();
showToast(`收起延迟已更新`, 'info');
});
// Toast 时长
document.getElementById('fs-sv-toastDuration').addEventListener('change', function() {
globalSettings.toastDuration = parseInt(this.value);
saveGlobalSettings();
showToast(`提示时长已更新`, 'info');
});
// 上传字体
document.getElementById('fs-sv-upload-btn').addEventListener('click', () => {
fontFileInput.click();
});
// 全部清除自定义字体
const clearBtn = document.getElementById('fs-sv-clearFonts');
if (clearBtn) {
clearBtn.addEventListener('click', () => {
if (!confirm('确认清除所有自定义字体?此操作不可撤销。')) return;
// 移除所有 font-face
customFonts.forEach(font => {
const faceId = 'fs-fontface-' + CSS.escape(font.name.replace(/\s+/g, '-'));
const faceEl = document.getElementById(faceId);
if (faceEl) faceEl.remove();
removeFontSettings(font.value);
});
// 如果当前激活的是自定义字体,重置
if (customFonts.some(f => f.value === activeFontValue)) {
activeFontValue = '';
saveToStorage(STORAGE_KEY_ACTIVE_FONT, activeFontValue);
applyFont('');
}
customFonts = [];
saveToStorage(STORAGE_KEY_CUSTOM_FONTS, customFonts);
renderSettingsView();
showToast('已清除所有自定义字体', 'info');
});
}
// 重置按钮位置
document.getElementById('fs-sv-resetPos').addEventListener('click', () => {
btnSide = 'right';
btnY = 60;
saveBtnPosition();
applyBtnPosition();
showToast('按钮位置已重置', 'info');
});
// 重置当前站点设置
document.getElementById('fs-sv-resetSite').addEventListener('click', () => {
if (!confirm('确认重置当前站点的所有字体设置?')) return;
activeFontValue = '';
isEnabled = true;
fontSettings = {};
saveToStorage(STORAGE_KEY_ACTIVE_FONT, '');
saveToStorage(STORAGE_KEY_ENABLED, true);
saveToStorage(STORAGE_KEY_FONT_SETTINGS, {});
applyFont('');
document.getElementById('fs-enabled-toggle').checked = true;
expandedSettingsSet.clear();
renderFontList();
showToast('当前站点设置已重置', 'info');
});
}
// ==================== 设置视图切换 ====================
function toggleSettingsView() {
settingsViewActive = !settingsViewActive;
const listContainer = document.getElementById('fs-font-list');
const settingsView = document.getElementById('fs-settings-view');
const gearBtn = document.getElementById('fs-header-gear-btn');
const toggleRow = panel.querySelector('.fs-toggle-row');
if (settingsViewActive) {
listContainer.style.display = 'none';
toggleRow.style.display = 'none';
settingsView.style.display = 'block';
gearBtn.classList.add('fs-gear-active');
renderSettingsView();
} else {
listContainer.style.display = '';
toggleRow.style.display = '';
settingsView.style.display = 'none';
gearBtn.classList.remove('fs-gear-active');
}
}
// ==================== 面板控制 ====================
function togglePanel() {
panelVisible = !panelVisible;
if (panelVisible) {
// 打开面板时回到字体列表视图
if (settingsViewActive) toggleSettingsView();
positionPanel();
panel.classList.add('fs-show');
overlay.classList.add('fs-show');
triggerBtn.classList.add('fs-active');
if (idleTimer) clearTimeout(idleTimer);
} else {
panel.classList.remove('fs-show');
overlay.classList.remove('fs-show');
triggerBtn.classList.remove('fs-active');
// 关闭面板时退出设置视图
if (settingsViewActive) {
settingsViewActive = false;
document.getElementById('fs-font-list').style.display = '';
panel.querySelector('.fs-toggle-row').style.display = '';
document.getElementById('fs-settings-view').style.display = 'none';
document.getElementById('fs-header-gear-btn').classList.remove('fs-gear-active');
}
resetIdleTimer();
}
}
function closePanel() {
if (!panelVisible) return;
panelVisible = false;
panel.classList.remove('fs-show');
overlay.classList.remove('fs-show');
triggerBtn.classList.remove('fs-active');
if (settingsViewActive) {
settingsViewActive = false;
document.getElementById('fs-font-list').style.display = '';
panel.querySelector('.fs-toggle-row').style.display = '';
document.getElementById('fs-settings-view').style.display = 'none';
document.getElementById('fs-header-gear-btn').classList.remove('fs-gear-active');
}
resetIdleTimer();
}
// ==================== Toast ====================
let toastTimer = null;
function showToast(msg, type = 'info') {
toast.textContent = msg;
toast.className = 'fs-toast-' + type + ' fs-toast-show';
if (toastTimer) clearTimeout(toastTimer);
toastTimer = setTimeout(() => { toast.classList.remove('fs-toast-show'); }, globalSettings.toastDuration || 2000);
}
// ==================== 事件绑定 ====================
overlay.addEventListener('click', closePanel);
panel.querySelector('.fs-header-close').addEventListener('click', closePanel);
document.getElementById('fs-header-gear-btn').addEventListener('click', (e) => {
e.stopPropagation();
toggleSettingsView();
});
const enabledToggle = document.getElementById('fs-enabled-toggle');
enabledToggle.checked = isEnabled;
enabledToggle.addEventListener('change', () => {
isEnabled = enabledToggle.checked;
saveToStorage(STORAGE_KEY_ENABLED, isEnabled);
if (isEnabled && activeFontValue) applyFont(activeFontValue);
else applyFont('');
showToast(isEnabled ? `字体替换已启用(${CURRENT_HOST})` : `字体替换已关闭(${CURRENT_HOST})`, 'info');
});
fontFileInput.addEventListener('change', (e) => {
handleFontFileUpload(e.target.files);
e.target.value = '';
// 如果设置视图打开着,刷新它
if (settingsViewActive) renderSettingsView();
});
// ==================== 初始化 ====================
function initExpandedSettings() {
const allFonts = [...PRESET_FONTS, ...customFonts];
allFonts.forEach(font => {
if (font.value && hasNonDefaultSettings(font.value)) {
expandedSettingsSet.add(font.value);
}
});
}
function init() {
reloadCustomFonts();
initExpandedSettings();
renderFontList();
clampBtnY();
applyBtnPosition();
if (isEnabled && activeFontValue) applyFont(activeFontValue);
setTimeout(() => { triggerBtn.classList.remove('fs-entering'); }, 500);
resetIdleTimer();
}
if (document.readyState === 'complete' || document.readyState === 'interactive') {
init();
} else {
document.addEventListener('DOMContentLoaded', init);
}
})();