Chrome如何通过脚本全局替换指定字体栈的Segoe UI为Segoe UI Variable Small
解决方案
可以通过以下TamperMonkey脚本完成需求,脚本只会修改包含Segoe UI的字体栈规则,不会对未使用该字体栈的站点产生任何影响。
完整脚本代码
// ==UserScript== // @name 替换Segoe UI为Segoe UI Variable Small // @namespace http://tampermonkey.net/ // @version 0.1 // @description 把所有字体栈中的Segoe UI替换为Segoe UI Variable Small // @match *://*/* // @grant none // ==/UserScript== (function() { 'use strict'; // 仅Windows系统生效 if (!navigator.userAgent.includes('Windows')) return; const replaceFont = (style) => { if (!style || !style.fontFamily) return; const fontFamily = style.fontFamily; if (fontFamily.includes('Segoe UI') && !fontFamily.includes('Segoe UI Variable')) { style.fontFamily = fontFamily.replace(/['"]?Segoe UI['"]?/g, '"Segoe UI Variable Small"'); } }; // 处理现有样式表 const processStylesheets = () => { for (let i = 0; i < document.styleSheets.length; i++) { try { const sheet = document.styleSheets[i]; const rules = sheet.cssRules || sheet.rules; if (!rules) continue; for (let j = 0; j < rules.length; j++) { const rule = rules[j]; if (rule.style) { replaceFont(rule.style); } // 处理@media等嵌套规则 if (rule.cssRules) { for (let k = 0; k < rule.cssRules.length; k++) { if (rule.cssRules[k].style) { replaceFont(rule.cssRules[k].style); } } } } } catch (e) { // 跨域样式表无法访问直接跳过 continue; } } }; // 处理元素内联样式 const processInlineStyles = (root = document) => { const elements = root.querySelectorAll('*'); elements.forEach(el => { if (el.style) { replaceFont(el.style); } }); }; // 初次执行 processStylesheets(); processInlineStyles(); // 监听动态加载的DOM和样式 const observer = new MutationObserver(mutations => { mutations.forEach(mutation => { if (mutation.addedNodes.length) { mutation.addedNodes.forEach(node => { if (node.nodeType === Node.ELEMENT_NODE) { if (node.tagName === 'STYLE' || node.tagName === 'LINK') { // 新增样式表延迟处理,等加载完成 setTimeout(processStylesheets, 200); } else { processInlineStyles(node); } } }); } }); }); observer.observe(document.documentElement, { childList: true, subtree: true }); })();
使用方法
- 打开TamperMonkey扩展面板,选择「创建新脚本」,清空默认生成的代码,粘贴上述代码后保存即可生效
- 脚本默认匹配所有站点,可修改
@match字段调整生效范围,也可新增@exclude字段排除不需要生效的站点 - 若要调整替换的字体样式,直接把代码中的
"Segoe UI Variable Small"修改为对应字体名称即可
注意事项
- 需提前确保系统中已正确安装Segoe UI Variable字体系列,否则脚本不会生效,会自动回退为原有Segoe UI字体
- 脚本仅修改字体栈中
Segoe UI对应的位置,不会改变原有字体栈的其他字体优先级,也不会修改未使用Segoe UI的样式规则,不会干扰其他站点的显示效果
内容的提问来源于stack exchange,提问作者ProximanovaMetropolis
相关产品推荐
相关产品推荐

