简体   繁体   English

动态加载Web字体

[英]Dynamically load web font

I'm new to this web font thing. 我是这个网络字体的新手。 I understand that a certain font can be downloaded from a URL and used in a web page. 我知道某个字体可以从URL下载并在网页中使用。

My question is: is it possible to load a web font dynamically depending on the user input? 我的问题是:是否可以根据用户输入动态加载Web字体? Simply scenario: user type in some text in the text field and select a font name which was not loaded yet. 简单的场景:用户在文本字段中键入一些文本,然后选择尚未加载的字体名称。 Some javascript code is triggered to dynamically load a web font resource. 触发一些javascript代码以动态加载Web字体资源。 Is this possible? 这可能吗?

Try this (for Google web fonts): 试试这个(对于Google网络字体):

<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://jsfiddle.net/zejz2tkp/1/

This code is bassed on this post: http://amirush.blogspot.ro/2013/07/dynamic-loading-of-web-fonts.html 此代码基于以下帖子: http//amirush.blogspot.ro/2013/07/dynamic-loading-of-web-fonts.html

You can also use one of the existent answers: Load external font with javascript and jquery or dynamically load fonts html jquery 您还可以使用现有答案之一: 使用javascript和jquery加载外部字体动态加载字体html jquery

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM