How to import font file using JavaScript?

末鹿安然 提交于 2019-12-18 05:03:07

问题


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?


回答1:


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 use document.write (or document.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.




回答2:


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




回答3:


No. There's not. Javascript can manipulate the DOM, but it doesn't care about formatting.




回答4:


yes you can:

document.body.style.fontFamily = '...';

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




回答5:


There is an experimental technology "CSS Font Loading API" that allows to load and use font in javascript. Currently working in chrome and firefox.

fetch('/static/media/ProximaNova-Regular.otf')
        .then(resp => resp.arrayBuffer())
        .then(font => {
            const fontFace = new FontFace('Proxima-Nova', font);
            document.fonts.add(fontFace);
            document.body.style.fontFamily = '"Proxima-Nova", Arial';
        })


来源:https://stackoverflow.com/questions/5586845/how-to-import-font-file-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!