2014-10-02 51 views
0

我試圖做這樣的事情......從選擇菜單中選擇字體,然後調用jquery函數並將頭文件前置,加載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

嘗試使用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()); 
     } 
    }); 
}); 
+0

謝謝你的幫助,但它不工作對我來說......我犯了一些錯誤嗎?這段代碼是否正確? :) – Patrik 2014-10-02 08:37:42

+1

我會盡量在接下來的幾分鐘內爲你製作一個小提琴。 – heroin 2014-10-02 08:40:33

+1

我創建了一個小提琴http://jsfiddle.net/heroin62134/3tqhgg8r/3/ – heroin 2014-10-02 10:08:32

相關問題