我有一个用 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]);
一切工作正常,除了 Safari 中的文本非常粗体
属性
-webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-rendering: optimizeLegibility;
不解决我的问题
在 CSS 代码中,默认指定字体粗细值会很有用。你尝试过吗?
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;
font-weight: 400;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
`;
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]);