通过 JavaScript 更改字体 [英] Font-Face changing via JavaScript
问题描述
所以基本的工作流程是这样的:
So the basic workflow is this:
字体的异步文件上传(已经完成).
Asynchronous file upload of a font (this is already done).
获取 URL(完成).
Get the URL (done).
将字体更改为新 URL.
Change the font to the new URL.
我意识到这需要通过 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.
推荐答案
您可以使用 @font-face
规则创建一个新的 元素并附加它到
document
的head
:
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);
当然,您可能还需要提供所有必要的字体格式和 URL,除非您只担心对现代桌面浏览器的支持(在这种情况下,您将只使用 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屋!