如何使用 JavaScript 导入字体文件?
CSS has a @font-face
rule which allows us to "use" custom fonts.
Does JavaScript have this functionality?
More specifically, is it possible to "use" custom fonts without using the CSS @font-face
rule?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
2023 年更新:使用
FontFace
作为在 MDN 上的 CSS 字体加载 API 上找到:
我' m 将
url_to_font_name
变量分隔开,以表明它可以是动态生成的字符串。与 CSS 相比,这是我认为使用 JavaScript 加载字体的最大好处。Update 2023: use
FontFace
As found on CSS Font Loading API on MDN:
I'm separating the
url_to_font_name
variable out to indicate that it can be a dynamically generated string. This the biggest benefit I see to use JavaScript to load fonts compared to CSS.如果您了解 CSS,您可以使用
document.write
动态附加样式表...我想这将算作使用 CSS,但它会起作用if you know CSS you can use
document.write
to append a style sheet dynamically... I guess that would count as using CSS, but it would work除了使用
@font-face
规则之外,没有其他方法可以使浏览器从网络加载字体。理论上,您可以从 JavaScript 创建@font-face
规则,而无需使用document.write
(或document.createElement(" style")
等),如果您使用 CSS 对象模型;但目前我不指望在任何浏览器中实现这一点。There is no way to cause the browser to load a font from the network other than with a
@font-face
rule. You could theoretically create that@font-face
rule from JavaScript without having to usedocument.write
(ordocument.createElement("style")
etc), if instead you used the CSS Object Model; but I wouldn't count on that to be implemented in any browser at the moment.不,没有。 JavaScript 可以操作 DOM,但它不关心格式。
No. There's not. Javascript can manipulate the DOM, but it doesn't care about formatting.
有一种实验性技术“CSS Font Loading API”允许在 javascript 中加载和使用字体。目前在 chrome 和 firefox 上工作。
There is an experimental technology "CSS Font Loading API" that allows to load and use font in javascript. Currently working in chrome and firefox.
是的,你可以:
这是一个小提琴: http://jsfiddle.net/maniator/QMZ8N/
这个只向元素添加预定义字体。
这不向页面添加字体样式。为此你可能必须使用 CSS
yes you can:
here is a fiddle: http://jsfiddle.net/maniator/QMZ8N/
this only adds a predefined font to an element.
This does NOT add a font style to the page. for that you might have to use CSS