2013-05-14 103 views
16

我希望能夠讓用戶選擇他們希望顯示頁面的字體。Here是Google建議您使用JavaScript進行操作的方式。在頁面加載後動態加載谷歌字體

WebFontConfig = { 
    google: { 
     families: ['Tangerine', 'Cantarell'] 
    } 
}; 

(function() { 
     var wf = document.createElement('script'); 
     wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + 
      '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js'; 
     wf.type = 'text/javascript'; 
     wf.async = 'true'; 
     var s = document.getElementsByTagName('script')[0]; 
     s.parentNode.insertBefore(wf, s); 
     })(); 

我該如何修改它以便在頁面加載後重新獲得字體?

回答

24

閱讀本GitHub庫的WebFont.load命令:

https://github.com/typekit/webfontloader

您可以加載您想要動態任何字體:

<script src="http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js"></script> 
    <script> 
     WebFont.load({ 
        google: { 
          families: ['Droid Sans', 'Droid Serif'] 
        } 
     }); 
    </script> 
+0

完美多謝 – Alexis

+4

請務必使用在生產中的特定版本。否則不會有緩存。 – sanmai

+0

@sanmai:那不是真的......有最新版本的緩存長達1年。我認爲這個問題更多的是一個buggy版本會打破你的網站。 –