碎片時間學(xué)編程「355]:將給定的 CSS 代碼插入到當前文檔中

使用 Document.createElement() 創(chuàng)建一個新的樣式元素并將其類型設(shè)置為 text/css。
使用 Element.innerText 將值設(shè)置為給定的 CSS 字符串。?
使用 Document.head 和 Element.appendChild() 將新元素附加到文檔頭。?
返回新創(chuàng)建的樣式元素。
const injectCSS = css => { ?let el = document.createElement('style'); ?el.type = 'text/css'; ?el.innerText = css; ?document.head.appendChild(el); ?return el;};
示例:
injectCSS('body { background-color: #000 }');// '<style type="text/css">body { background-color: #000 }</style>'
更多內(nèi)容請訪問我的網(wǎng)站:https://www.icoderoad.com
標簽: