我试着做这样的东西。。。从选择菜单中选择字体,然后调用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());
});
尝试使用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());
}
});
});