简体   繁体   English

如何仅更改一个元素的字体系列 - nextjs

[英]How to change font family only for one element - nextjs

My project has a global font.我的项目有一个全局字体。 but for only one element I get font families randomly from a hosted url.但是对于只有一个元素,我从托管的 url 中随机获取字体系列。 example:例子:

https://minio.kadoxa.com/file/fonts/Parnian.ttf

my page is a CSR.我的页面是 CSR。

now How I can use this font for my element?现在我如何为我的元素使用这种字体?

You can dynamically load fonts with Javascript.您可以使用 Javascript 动态加载字体。

const fontFace = new FontFace(newFontName, `url(${newFontUrl})`);
fontFace.load().then((loadedFace: FontFace) => {
  document.fonts.add(loadedFace);
  setFontFamily(newFontName);
};

Here is an example dynamically loading Google Fonts in NextJS.这是在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM