[英]How to change font family only for one element - nextjs
我的项目有一个全局字体。 但是对于只有一个元素,我从托管的 url 中随机获取字体系列。 例子:
https://minio.kadoxa.com/file/fonts/Parnian.ttf
我的页面是 CSR。
现在我如何为我的元素使用这种字体?
您可以使用 Javascript 动态加载字体。
const fontFace = new FontFace(newFontName, `url(${newFontUrl})`);
fontFace.load().then((loadedFace: FontFace) => {
document.fonts.add(loadedFace);
setFontFamily(newFontName);
};
这是在 NextJS 中动态加载 Google 字体的示例。
import { useState } from 'react';
import type { NextPage } from 'next';
import * as font from 'random-google-font';
const Home: NextPage = () => {
const [fontFamily, setFontFamily] = useState('cursive');
const updateFont = async () => {
const response = await font.get();
if (response.length < 1) return;
const newFontName = response[0].local[0].substring(
1,
response[0].local[0].length - 1
);
const newFontUrl = response[0].url.ttf;
const fontFace = new FontFace(newFontName, `url(${newFontUrl})`);
const loadedFace = await fontFace.load();
document.fonts.add(loadedFace);
setFontFamily(newFontName);
};
return (
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: '1em',
}}
>
<span style={{ fontFamily }}>Hello S.M_Emamian!</span>
<div style={{ cursor: 'pointer' }} onClick={updateFont}>
🔁
</div>
</div>
);
};
export default Home;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.