我是一名新手,对于这个网络字体的事情并不了解。我知道可以从URL中下载某种字体并在网页中使用。
我的问题是:是否可以根据用户输入动态加载网络字体?简单的场景是,用户在文本字段中输入一些文本并选择一个还没有被加载的字体名称。触发一些JavaScript代码来动态加载网络字体资源。这可能吗?
我的问题是:是否可以根据用户输入动态加载网络字体?简单的场景是,用户在文本字段中输入一些文本并选择一个还没有被加载的字体名称。触发一些JavaScript代码来动态加载网络字体资源。这可能吗?
试试这个(针对Google Web字体):
<span>Select font:</span>
<select onchange=fontSelected(event)>
<option value="default">Browser Default</option>
<option value="Droid+Sans">Droid Sans</option>
<option value="Open+Sans">Open Sans</option>
</select>
<h1 id="theText">This is a sample text...</h1>
function fontSelected(e){
var select = e.target;
if (select.selectedIndex > 0) { // web font
var fontID = select.options[select.selectedIndex].value;
if (!document.getElementById(fontID)) {
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = fontID;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://fonts.googleapis.com/css?family='+fontID;
link.media = 'all';
head.appendChild(link);
}
document.getElementById("theText").style.fontFamily = select.options[select.selectedIndex].innerHTML;
}else{ // default browser font
document.getElementById("theText").style.fontFamily = null;
}
}
http://jsfiddle.net/zejz2tkp/1/
这段代码基于这篇文章:http://amirush.blogspot.ro/2013/07/dynamic-loading-of-web-fonts.html
您也可以使用其中一个已有的答案:Load external font with javascript and jquery或dynamically load fonts html jquery