通过 JavaScript 更改字体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11355147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Font-Face changing via JavaScript
提问by Ry-
So the basic workflow is this:
所以基本的工作流程是这样的:
Asynchronous file upload of a font (this is already done).
Get the URL (done).
Change the font to the new URL.
字体的异步文件上传(这已经完成)。
获取 URL(完成)。
将字体更改为新 URL。
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 来完成,但我似乎无法弄清楚如何通过 JavaScript 访问它。
回答by Ry-
You can create a new <style>
element with the @font-face
rule and append it to the document
's head
:
您可以<style>
使用@font-face
规则创建一个新元素并将其附加到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);
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).
当然,您可能还需要提供所有必要的字体格式和 URL,除非您只担心对现代桌面浏览器的支持(在这种情况下,您将只使用 WOFF——我认为这是合理的,因为您提到的其他功能)。
回答by Cybernetic
Define a FontFace object:
定义一个 FontFace 对象:
new_font = new FontFace('conthrax', 'url(fonts/conthrax-sb.ttf)')
Call its load method to download the font:
调用它的 load 方法来下载字体:
new_font.load().then(function(loaded_face) {
// use font here
}).catch(function(error) {
});
... this returns a Promise, which when resolved passes the loaded FontFace.
...这将返回一个 Promise,它在解析时传递加载的 FontFace。
Add the loaded font to the document:
将加载的字体添加到文档中:
new_font.load().then(function(loaded_face) {
// use font here
document.fonts.add(loaded_face)
}).catch(function(error) {
});
Use the font as needed (e.g. in Azle):
根据需要使用字体(例如在Azle 中):
az.style_text('my_title', 1, {
"font-family" : "conthrax"
})