React站点自定义字体切换功能在Safari中显示过粗问题求助
Safari自定义切换字体显示过粗的解决方案
我开发了一个基于React的网站,支持用户自主切换页面字体,核心实现代码如下:
useEffect(() => { if (!!font) { const fontUrl = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(font)}:wght@400;700&ital,wght@0,400;0,700;1,400;1,700&display=swap`; const style = document.createElement('style'); style.innerText = ` @import url('${fontUrl}'); body { font-family: '${font}', 'Source Sans Pro', sans-serif !important; } `; document.head.appendChild(style); // Cleanup function to remove the style when the component is unmounted or if the font prop changes return () => { document.head.removeChild(style); }; } }, [font]);
该功能在Chrome浏览器中运行正常,但在Safari浏览器中文字显示异常粗重。我尝试过以下CSS属性,但问题仍未解决:
-webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-rendering: optimizeLegibility;
Chrome显示正常,Safari中字体明显偏粗,以下是针对该问题的可行解决方案:
1. 修正Google Fonts URL参数
当前URL重复声明了wght参数,可能导致Safari加载字体时权重冲突。简化URL参数:
const fontUrl = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(font)}:ital,wght@0,400;0,700;1,400;1,700&display=swap`;
2. 显式指定全局字体权重
在body样式中明确设置默认字体权重,避免Safari自动套用加粗规则,同时给需要加粗的元素单独设置font-weight:700:
body { font-family: '${font}', 'Source Sans Pro', sans-serif !important; font-weight: 400 !important; }
3. 改用@font-face直接加载字体
Safari对@import的字体加载逻辑存在差异,直接创建@font-face规则可以更精准控制字体加载:
useEffect(() => { if (font) { const fontEncoded = encodeURIComponent(font); // 从Google Fonts的CSS中提取对应字体的woff2链接替换下方的占位符 const style = document.createElement('style'); style.innerText = ` @font-face { font-family: '${font}'; font-style: normal; font-weight: 400; src: url(https://fonts.gstatic.com/s/${fontEncoded.toLowerCase()}/[具体文件名].woff2) format('woff2'); } @font-face { font-family: '${font}'; font-style: normal; font-weight: 700; src: url(https://fonts.gstatic.com/s/${fontEncoded.toLowerCase()}/[具体文件名].woff2) format('woff2'); } @font-face { font-family: '${font}'; font-style: italic; font-weight: 400; src: url(https://fonts.gstatic.com/s/${fontEncoded.toLowerCase()}/[具体文件名].woff2) format('woff2'); } @font-face { font-family: '${font}'; font-style: italic; font-weight: 700; src: url(https://fonts.gstatic.com/s/${fontEncoded.toLowerCase()}/[具体文件名].woff2) format('woff2'); } body { font-family: '${font}', 'Source Sans Pro', sans-serif !important; font-weight: 400; } `; document.head.appendChild(style); return () => document.head.removeChild(style); } }, [font]);
注:具体字体文件URL可通过打开Google Fonts生成的CSS链接查看提取。
4. 添加Safari专属的字体微调属性
在全局样式中添加以下属性,弱化Safari的粗体渲染效果:
-webkit-text-stroke: 0.3px rgba(0, 0, 0, 0.1);
内容的提问来源于stack exchange,提问作者Diana Vargas
相关产品推荐
相关产品推荐

