通过选择菜单加载外部字体

时间:2014-10-02 06:51:29

标签: jquery fonts font-face external

我尝试做这样的事情......从选择菜单中选择字体,然后调用jquery函数并将css添加到head,加载exernal字体并更改字体系列" #target" DIV。但它不起作用......

HTML

<select id="sel_font">
    <option value="Roboto-Regular"></option>
    <option value="Roboto-Thin"></option>
    <option value="Roboto-ThinItalic"></option>
</select>
<div id="target">
    some text
</div>

的jQuery

 $('#sel_font').change(function() {
    $("head").prepend('<style type=\"text/css\"> @font-face { font-family: \" ' + $(this).val() + '\"; src: url(\"fonts/' + $(this).val() + '.ttf\") format(\"truetype\"); } </style>');
    $("#target").css("font-family", $(this).val());
  });

1 个答案:

答案 0 :(得分:1)

尝试使用Google webfont loader

//blank urls, you should use your own 
//(because of Cross-Origin policy they will not be loaded - 
//for this example it does not matter, because these fonts are embedded in a browser
var urls = {
    "Sans-serif": "http://www.corsproxy.com/github.com/Rydgel/archlinux/raw/master/.fonts/CAMBRIA.TTC",
    "Consolas": "http://www.corsproxy.com/github.com/Rydgel/archlinux/raw/master/.fonts/CAMBRIA.TTC"
};

//all fonts should be inserted in ``head`` in a one single ``style`` tag
var text = '<style type=\"text/css\">';
for (var k in urls) {
    text += '@font-face { font-family: \"' + k + '\"; src: url(\"' + urls[k] + '\") format(\"truetype\");  } '; 
}
$("head").prepend(text + '</style>');

$('#sel_font').change(function() {
    console.log('Inside a change function: '+ $('#sel_font').val())

    WebFont.load({
        custom: { 
            families: [$('#sel_font').val()]
        },
        active: function () { 
            console.log('Inside a callback: ' + $('#sel_font').val());
            $("#target").css("font-family", $('#sel_font').val());
        }
    });
});