如何使用userstyles为网页所有字体栈添加适配PUA编码的自定义字体
方案1:Stylus 全局注入(无需逐个适配选择器)
直接用通配规则结合unicode-range参数实现精准生效,不需要定位站点的具体元素选择器,完全不会破坏站点原有字体的显示效果:
@font-face { font-family: "CustomPUAFont"; /* 此处local内填你本地安装的字体的实际系统名称,可通过字体管理工具查看 */ src: local("你的自定义字体系统名称"); /* 仅对你使用的PUA区间字符生效,其他字符沿用站点原有字体 */ unicode-range: U+E000-E1FF; } * { font-family: "CustomPUAFont", sans-serif !important; }
如果要完全保留站点原有字体栈,只把自定义字体插入到最高优先级,把上面*选择器的样式改成以下写法即可:
* { font-family: "CustomPUAFont", inherit !important; }
方案2:Tampermonkey 油猴脚本(更优方案,覆盖动态加载内容)
这个方案适配性更强,不需要依赖样式扩展,自动覆盖所有站点的内联样式、外部样式表,以及页面加载后动态生成的内容,无需任何站点适配操作:
- 提前注入仅对E000-E1FF区间生效的自定义字体声明
- 自动遍历所有已有元素,把自定义字体插入到其字体栈最前端
- 用MutationObserver监听DOM变化,动态新增的内容也会自动应用规则
核心代码示例:
// 插入自定义字体规则 const customFontStyle = document.createElement('style'); customFontStyle.textContent = ` @font-face { font-family: "PUACustomFont"; src: local("你的自定义字体系统名称"); unicode-range: U+E000-E1FF; } `; document.head.appendChild(customFontStyle); // 给已有元素追加自定义字体 document.querySelectorAll('*').forEach(el => { const originFont = getComputedStyle(el).fontFamily; el.style.fontFamily = `"PUACustomFont", ${originFont}`; }); // 监听动态新增的DOM元素自动适配 const observer = new MutationObserver(mutations => { mutations.forEach(mut => { mut.addedNodes.forEach(node => { if (node.nodeType === 1) { const originFont = getComputedStyle(node).fontFamily; node.style.fontFamily = `"PUACustomFont", ${originFont}`; } }); }); }); observer.observe(document.body, { childList: true, subtree: true });
内容的提问来源于stack exchange,提问作者Peter Cyrus
相关产品推荐
相关产品推荐

