使用 javascript 和 jquery 加载外部字体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7282151/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:37:23  来源:igfitidea点击:

Load external font with javascript and jquery

javascriptjqueryhtmlfonts

提问by gabitzish

I have a < p > element created dynamically with jquery, and I want to style it with a custom font that I have on my hard drive.

我有一个用 jquery 动态创建的 < p > 元素,我想用我硬盘上的自定义字体来设置它的样式。

Could you sugest me a method to load that font and apply it to this element.

你能给我一个方法来加载那个字体并将它应用到这个元素上。

Right now, the object looks something like:

现在,该对象看起来像:

$("<p>").css({ fontFamily : "Arial",
               fontSize: "13px",
               color: "#000"});

I want to replace fontFamily : "Arial" with my custom font.

我想用我的自定义字体替换 fontFamily : "Arial"。

Thanks, Gabriel

谢谢,加布里埃尔

回答by gabitzish

This piece of code does all the job:

这段代码完成了所有工作:

$("head").prepend("<style type=\"text/css\">" + 
                                "@font-face {\n" +
                                    "\tfont-family: \"myFont\";\n" + 
                                    "\tsrc: local('?'), url('myFont.otf') format('opentype');\n" + 
                                "}\n" + 
                                    "\tp.myClass {\n" + 
                                    "\tfont-family: myFont !important;\n" + 
                                "}\n" + 
                            "</style>");

回答by gabitzish

I found a good solution using fontface plugin for jquery. http://www.sitepoint.com/the-fontface-jquery-plugin/

我找到了一个很好的解决方案,使用 jquery 的 fontface 插件。 http://www.sitepoint.com/the-fontface-jquery-plugin/

回答by 472084

You will need to add some CSS to your style sheet - You can find the right CSSS to add here: How do I load external fonts into an HTML document?

您需要在样式表中添加一些 CSS - 您可以在此处找到要添加的正确 CSSS:如何将外部字体加载到 HTML 文档中?

You can then change the font name with whatever its called eg:

然后,您可以使用其名称更改字体名称,例如:

$("<p>").css({ fontFamily : "Kimberley",
               fontSize: "13px",
               color: "#000"});

EDIT:What would be better is to add a class in your stylesheet for the

编辑:更好的是在样式表中为

tag and then add that class to to your p with jquery

标记,然后使用 jquery 将该类添加到您的 p

p.example{ font-family:Arial, Helvetica, sans-serif; }

$("<p>").addClass("example");

回答by Graeme Leighfield

Personally I use cufon.

我个人使用cufon。

Works on 99% of browsers out there!

适用于 99% 的浏览器!

http://cufon.shoqolate.com/generate/

http://cufon.shoqolate.com/generate/

Enjoy!

享受!