您可以使用JavaScript将style
元素附加到head
中,例如以下代码片段。
演示
let head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style'),
fonts = {
"Animais-1.ttf": "http://ggt-des.br/styles/fontes/Animais-1.ttf",
"Animais-2.ttf": "http://ggt-des.br/styles/fontes/Animais-2.ttf",
"Animais.ttf": "http://ggt-des.br/styles/fontes/Animais.ttf",
"CPRM_Fontes.ttf": "http://ggt-des.br/styles/fontes/CPRM_Fontes.ttf",
"ESRI-Electric.ttf": "http://ggt-des.br/styles/fontes/ESRI-AMFM-Electric.ttf",
"ESRI-AMFM-Gas.ttf": "http://ggt-des.br/styles/fontes/ESRI-AMFM-Gas.ttf"
};
head.appendChild(style);
style.type = 'text/css';
let css = Object.entries(fonts).map(v => `@font-face {
font-family: "${v[0].split('.')[0]}";
src: url(${v[1]});
font-weight: normal;
font-style: normal;
}`).join('');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
.one {
font-family: "Animais-1";
}
.two {
font-family: "Animais-2";
}
.three {
font-family: "Animais";
}
.four {
font-family: "CPRM_Fontes";
}
.five {
font-family: "ESRI-Electric";
}
.six {
font-family: "ESRI-AMFM-Gas";
}
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>
<div class="six">6</div>
你可以使用 SASS 来使用
mixin
,但需要创建
.scss
文件,而不是
.css
。
在 .scss
文件中,需要创建 @mixin
,它类似于函数。
然后,需要使用 @include
调用该 mixin
并传递参数,这类似于调用函数。
MIXIN 示例
@mixin font-face($name, $path, $weight: null, $style: null){
@font-face {
font-family: quote($name);
font-style: $style;
font-weight: $weight;
src: $path;
}
}
@include font-face("Animais-2", "http://ggt-des.br/styles/fontes/Animais-1.ttf", 'normal', 'normal');
@include font-face("Animais-2", "http://ggt-des.br/styles/fontes/Animais-2.ttf", 'normal', 'normal');
@include font-face("Animais", "http://ggt-des.br/styles/fontes/Animais.ttf", 'normal', normal);
@include font-face("CPRM_Fontes", "http://ggt-des.br/styles/fontes/CPRM_Fontes.ttf", 'normal', 'normal');
@include font-face("ESRI-Electric", "http://ggt-des.br/styles/fontes/ESRI-Electric.ttf", 'normal', 'normal');
@include font-face("ESRI-AMFM-Gas", "http://ggt-des.br/styles/fontes/ESRI-AMFM-Gas.ttf", 'normal', 'normal');
ttf
。将它们转换为woff2
并使用它代替。首先,ttf
是系统字体格式,因此您的字体可能会因为与Web字体无关的问题而被拒绝,但是其次,woff2
(和woff
,但在2019年几乎没有理由使用v1 woff格式)是一种无损压缩格式,这意味着您的网站将更快地加载给用户。 - Mike 'Pomax' Kamermans