通过JavaScript更改字体 [英] Font-Face changing via JavaScript

查看:208
本文介绍了通过JavaScript更改字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本的工作流程是:

So the basic workflow is this:


  1. 字体的异步文件上传(已经完成)。

  1. Asynchronous file upload of a font (this is already done).

获取网址(已完成)。

将字体更改为新网址。

我意识到这需要通过font-face来完成,但我似乎无法弄清楚如何访问通过JavaScript。

I realize this needs to be done via font-face, but I can't seem to figure out how to access that via JavaScript.

推荐答案

您可以创建一个新的< style> 元素与 @ font-face 规则并将其附加到文档头部

You can create a new <style> element with the @font-face rule and append it to the document's head:

var newStyle = document.createElement('style');
newStyle.appendChild(document.createTextNode("\
@font-face {\
    font-family: " + yourFontName + ";\
    src: url('" + yourFontURL + "') format('yourFontFormat');\
}\
"));

document.head.appendChild(newStyle);

当然,您可能还需要提供所有必要的字体格式和网址,除非你只担​​心对现代桌面浏览器的支持(在这种情况下你只需要使用WOFF–我认为这是合理的,因为你提到的其他功能)。

Of course, you'll probably need to provide all the necessary font formats and URLs, too, unless you're only worried about support for modern desktop browsers (in which case you would just use WOFF – I assume that's reasonable, because of the other features you mentioned).

这篇关于通过JavaScript更改字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆