Ale*_*xis 21 javascript css jquery font-face google-font-api
我希望能够让用户选择他们希望页面显示的字体. 以下是Google建议您使用JavaScript执行此操作的方式.
WebFontConfig = {
google: {
families: ['Tangerine', 'Cantarell']
}
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
Run Code Online (Sandbox Code Playgroud)
如何修改这个以便我可以在页面加载后重新获取字体?
mcc*_*nnf 31
查看此github仓库中的WebFont.load命令:
https://github.com/typekit/webfontloader
您可以动态加载任何您想要的字体:
<script src="http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js"></script>
<script>
WebFont.load({
google: {
families: ['Droid Sans', 'Droid Serif']
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
Pie*_*lle 13
或者,如果您不想要第三方库:
function addStylesheetURL(url) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
document.getElementsByTagName('head')[0].appendChild(link);
}
// Load Tangerine & Cantarell
addStylesheetURL('https://fonts.googleapis.com/css2?family=Cantarell&family=Tangerine&display=swap');Run Code Online (Sandbox Code Playgroud)
h1 {
font-family: 'Cantarell', sans-serif;
}
p {
font-family: 'Tangerine', cursive;
font-size: 30px;
}Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
<title>Dynamically load google fonts after page has loaded</title>
<link rel="preconnect" href="https://fonts.gstatic.com">
</head>
<body>
<h1>Dynamically load google fonts after page has loaded</h1>
<p>Some text.</p>
</body>
</html>Run Code Online (Sandbox Code Playgroud)