是否可以使用 javascript 将字体动态更改为自定义字体?

Is it possible to dynamically change font to a custom typeface with javascript?

我一直在四处寻找,但似乎没有找到答案!

我一直在这样尝试:

document.body.style.fontFamily = "src(url(./webfonts/Compagnon-Bold.woff)";

等等:

document.body.style.fontFamily = "Script";

但是没有结果。 它也已经在 CSS 中:

 @font-face {
  font-family: 'Script';
  src: url(./webfonts/Compagnon-Bold.woff);
  }

您可能需要使用字体名称,而不是文件:document.body.style.fontFamily = "Compagnon Bold";。也就是说,您可能会更幸运(或更清晰的代码)设置 css 类 并切换它们而不是直接修改内联样式。

如果您支持现代浏览器,您可以使用新的 FontFace API:

此处,在此演示中,默认字体为 Roboto,当我们单击按钮时,主体的字体更改为 Sriracha 字体。

document.querySelector("button").addEventListener("click", function() {
  var myfont = new FontFace('Sriracha', 'url(https://fonts.gstatic.com/s/sriracha/v4/0nkrC9D4IuYBgWcI9NbfTwE.woff2) format("woff2")');
  myfont.load().then(function(loadedFont) {
    document.fonts.add(loadedFont);
    document.body.style.fontFamily = 'Sriracha';
  }).catch(function(error) {
    // error occurred
  });
});
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
body {
  font-family: 'Roboto', sans-serif;
}
<button>Change Font</button>
<h2>Almost before we knew it, we had left the ground.</h2>
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</div>