2017-09-21 36 views
0
fontFaceString = "@font-face {font-family: 'Lobster';font-style: normal;font-weight: normal;src:url('../../fonts/new_fonts/LOBSTER/Lobster-regular.ttf');}"; 

var newStyle = document.createElement('style'); 
newStyle.appendChild(document.createTextNode(fontFaceString)); 
document.head.appendChild(newStyle); 

我必須動態添加多個字體。我只是想添加一個字體與上面的代碼片段,它被添加到樣式標記但不正確渲染。動態添加的字體工作不正常

+0

提供一個例子jsfiddle或您的實際頁面 – dev

回答

1

中有JS特殊功能的添加名爲insertRule() CSS規則,先在你head標記添加<style></style>(無需從JS做到這一點),然後添加以下代碼:

var sheet = window.document.styleSheets[0]; 
sheet.insertRule("@font-face {font-family: 'Lobster';font-style: normal;font-weight: normal;src:url('../../fonts/new_fonts/LOBSTER/Lobster-regular.ttf');}", sheet.cssRules.length);