欢迎光临散文网 会员登陆 & 注册

碎片时间学编程「355]:将给定的 CSS 代码插入到当前文档中

2023-07-03 13:01 作者:路条编程  | 我要投稿


使用 Document.createElement() 创建一个新的样式元素并将其类型设置为 text/css。

使用 Element.innerText 将值设置为给定的 CSS 字符串。 

使用 Document.head 和 Element.appendChild() 将新元素附加到文档头。 

返回新创建的样式元素。

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>'

更多内容请访问我的网站:https://www.icoderoad.com


碎片时间学编程「355]:将给定的 CSS 代码插入到当前文档中的评论 (共 条)

分享到微博请遵守国家法律