代码之家  ›  专栏  ›  技术社区  ›  Mocktheduck

通过javascript将类似CSS的HTML注入到DOM中

  •  0
  • Mocktheduck  · 技术社区  · 7 年前

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

    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);
    

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

    基本上我有HTML+CSS+JS代码,我想把它放到 .js 文件而不是 .html . 我对网络开发很陌生,所以我不知道。这是可能的吗?

    4 回复  |  直到 7 年前
        1
  •  6
  •   user7637745 Alaa    7 年前

    您可以通过普通的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);
    <div class="my-element">Text</div>

    示例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);
    <DIV class=“my element”>文本</DIV>

    实施例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);
    <DIV class=“my element”>文本</DIV>
        2
  •  2
  •   zero298    7 年前

    是的,您是否尝试创建 <style> 标记,用规则填充它,然后注入它?

    const style = document.createElement("style");
    style.innerHTML = "#foo{background-color: green;}";
    document.head.appendChild(style);
    <div id="foo">Foo bar</div>
        3
  •  1
  •   SirPilan    7 年前

    你真的试过了吗?

    document.getElementById('myButton').onclick = function() {
      var sc = document.createElement('style');
      sc.innerHTML = "#myDiv { padding: 10px; border: 1px dashed blue; }";
      
      document.getElementById('myDiv').appendChild( sc );
    }
    <div id="myDiv">
      Test 123
    </div>
    <button id="myButton">Click Me!</button>

    如果你有 巨人 CSS文件。最好是加载文件本身。您可以创建一个 style 如上图所示标记并设置 href 属性来加载它。

        4
  •  1
  •   Salman Arshad    7 年前

    你可以用 CSSStyleSheet 用于操作样式表的接口。下面的示例演示如何操作现有样式表。此方法允许您指定插入规则的位置,而不总是在末尾附加它:

    document.querySelector("#button-1").addEventListener("click", function() {
      var sheet = document.querySelector("style").sheet;
      var color = "rgb(" + Math.floor(Math.random() * 256) + ", " + Math.floor(Math.random() * 256) + ", " + Math.floor(Math.random() * 256) + ")";
      sheet.insertRule("p { background-color: " + color + "; }", sheet.cssRules.length);
    });
    /* this stylesheet intentionally left blank */
    <button id="button-1">Modify Stylesheet</button>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum urna risus, non finibus sem fermentum eget. In at libero a justo molestie semper. Praesent sit amet massa justo. Donec aliquet lobortis justo tincidunt ultrices.</p>