通过JavaScript将类似HTML的CSS注入DOM

Moc*_*uck 0 html javascript css dom

我想知道我是否可以将CSS代码添加为字符串,就像我可以通过JavaScript添加HTML代码一样,例如:

var div = document.createElement("div");
div.innerHTML =
  '<div id="hs1"></div>\n' +
  '<div id="hs2"></div>\n' +
  '<div id="hs3"></div>\n'

document.body.appendChild(div);
Run Code Online (Sandbox Code Playgroud)

我能以类似的方式添加一个巨大的CSS代码吗?

基本上我有HTML + CSS + JS代码,我想放入.js文件而不是.html.我是网络开发的新手,所以我不知道.这甚至可能吗?

use*_*745 7

你可以通过vanilla JavaScript注入CSS:

  • 创建样式元素
  • 使用CSS将其内容设置为您的字符串
  • 将样式元素添加到DOM的头部

示例1(对于旧版浏览器):

// get the head and create a style element
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');

style.type = 'text/css';

// create your CSS as a string
var css = '.my-element { color: white; background: cornflowerblue; }';

// IE8 and below.
if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

// add it to the head
head.appendChild(style);
Run Code Online (Sandbox Code Playgroud)
<div class="my-element">Text</div>
Run Code Online (Sandbox Code Playgroud)

示例2(对于较新的浏览器):

// create a style element
var style = document.createElement('style');

// add the CSS as a string
style.innerHTML = '.my-element { color: white; background: cornflowerblue; }';

// add it to the head
document.getElementsByTagName('head')[0].appendChild(style);
Run Code Online (Sandbox Code Playgroud)
<div class="my-element">Text</div>
Run Code Online (Sandbox Code Playgroud)

例3(ES6):

// create a style element
const style = document.createElement('style');

// add the CSS as a string using template literals
style.appendChild(document.createTextNode(`
  .my-element { 
    color: white; 
    background: cornflowerblue; 
  }`
));

// add it to the head
const head = document.getElementsByTagName('head')[0];
head.appendChild(style);
Run Code Online (Sandbox Code Playgroud)
<div class="my-element">Text</div>
Run Code Online (Sandbox Code Playgroud)