Programing

Javascript로 CSS를 어떻게 추가합니까?

crosscheck 2020. 6. 17. 08:02
반응형

Javascript로 CSS를 어떻게 추가합니까?


strong { color: red }Javascript를 사용하여 CSS 규칙을 어떻게 추가 합니까?


DOM 레벨 2 CSS 인터페이스 ( MDN )를 사용하여이를 수행 할 수도 있습니다 .

var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

... (자연스럽게) IE8 및 이전 버전을 제외하고는 자체적으로 한계가 다른 표현을 사용합니다.

sheet.addRule('strong', 'color: red;', -1);

createElement-set-innerHTML 메소드와 비교하여 이론상 이점이 있습니다. innerHTML에 특수 HTML 문자를 넣을 염려가 없지만 실제로는 스타일 요소가 레거시 HTML의 CDATA이고 '<' 그리고 '&'는 스타일 시트에서 거의 사용되지 않습니다.

다음과 같이 스타일 시트를 추가하기 전에 스타일 시트가 필요합니다. 외부, 내장 또는 비어있는 기존 활성 스타일 시트 일 수 있습니다. 존재하지 않는 경우 현재 생성하는 유일한 표준 방법은 createElement를 사용하는 것입니다.


간단하고 직접적인 접근 방식은 style문서에 노드를 작성하고 추가하는 것 입니다.

// Your CSS as text
var styles = `
    .qwebirc-qui .ircwindow div { 
        font-family: Georgia,Cambria,"Times New Roman",Times,serif;
        margin: 26px auto 0 auto;
        max-width: 650px;
    }
    .qwebirc-qui .lines {
        font-size: 18px;
        line-height: 1.58;
        letter-spacing: -.004em;
    }

    .qwebirc-qui .nicklist a {
        margin: 6px;
    }
`

var styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = styles
document.head.appendChild(styleSheet)

Ben Blank의 솔루션은 IE8에서 작동하지 않습니다.

그러나 이것은 IE8에서 작동했습니다.

function addCss(cssCode) {
var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}

다음 은 새 텍스트 노드를 만드는 대신 사용할 수 있다는 점을 고려 하여 약간 업데이트 된 Chris Herring 솔루션 버전입니다 innerHTML.

function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';

    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }

    document.getElementsByTagName("head")[0].appendChild( style );
}

요소별로 요소 또는 클래스 속성을 추가 할 수 있습니다.

예를 들면 다음과 같습니다.

<a name="myelement" onclick="this.style.color='#FF0';">text</a>

Where you could do this.style.background, this.style.font-size, etc. You can also apply a style using this same method ala

this.className='classname';

If you want to do this in a javascript function, you can use getElementByID rather than 'this'.


This easy example of add <style> in head of html

var sheet = document.createElement('style');
sheet.innerHTML = "table th{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ "table ul {    margin-top: 0 !important;    margin-bottom: 0 !important;}\n"
+ "table td{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ ".messages.error{display:none !important;}\n"
+ ".messages.status{display:none !important;} ";

document.body.appendChild(sheet); // append in body
document.head.appendChild(sheet); // append in head

Source Dynamic style - manipulating CSS with JavaScript


YUI just recently added a utility specifically for this. See stylesheet.js here.


This is my solution to add a css rule at the end of the last style sheet list:

var css = new function()
{
    function addStyleSheet()
    {
        let head = document.head;
        let style = document.createElement("style");

        head.appendChild(style);
    }

    this.insert = function(rule)
    {
        if(document.styleSheets.length == 0) { addStyleSheet(); }

        let sheet = document.styleSheets[document.styleSheets.length - 1];
        let rules = sheet.rules;

        sheet.insertRule(rule, rules.length);
    }
}

css.insert("body { background-color: red }");

Another option is to use JQuery to store the element's in-line style property, append to it, and to then update the element's style property with the new values. As follows:

function appendCSSToElement(element, CssProperties)
        {
            var existingCSS = $(element).attr("style");

             if(existingCSS == undefined) existingCSS = "";

            $.each(CssProperties, function(key,value)
            {
                existingCSS += " " + key + ": " + value + ";";
            });

            $(element).attr("style", existingCSS);

            return $(element);
        }

And then execute it with the new CSS attributes as an object.

appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });

This may not necessarily be the most efficient method (I'm open to suggestions on how to improve this. :) ), but it definitely works.


Here's a sample template to help you get started

Requires 0 libraries and uses only javascript to inject both HTML and CSS.

The function was borrowed from the user @Husky above

Useful if you want to run a tampermonkey script and wanted to add a toggle overlay on a website (e.g. a note app for instance)

// INJECTING THE HTML
document.querySelector('body').innerHTML += '<div id="injection">Hello World</div>';

// CSS INJECTION FUNCTION
//https://stackoverflow.com/questions/707565/how-do-you-add-css-with-javascript
function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';
    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }
    document.getElementsByTagName("head")[0].appendChild( style );
}

// INJECT THE CSS INTO FUNCTION
// Write the css as you normally would... but treat it as strings and concatenate for multilines
insertCss(
  "#injection {color :red; font-size: 30px;}" +
  "body {background-color: lightblue;}"
)


Shortest One Liner

// One liner function:
const addCSS = (s)=>((d,e)=>{ e = d.createElement("style");e.innerHTML = s;d.head.appendChild(e)})(document);

// Usage: 
addCSS("body{ background:red; }")


Here's my general-purpose function which parametrizes the CSS selector and rules, and optionally takes in a css filename (case-sensitive) if you wish to add to a particular sheet instead (otherwise, if you don't provide a CSS filename, it will create a new style element and append it to the existing head. It will make at most one new style element and re-use it on future function calls). Works with FF, Chrome, and IE9+ (maybe earlier too, untested).

function addCssRules(selector, rules, /*Optional*/ sheetName) {
    // We want the last sheet so that rules are not overridden.
    var styleSheet = document.styleSheets[document.styleSheets.length - 1];
    if (sheetName) {
        for (var i in document.styleSheets) {
            if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(sheetName) > -1) {
                styleSheet = document.styleSheets[i];
                break;
            }
        }
    }
    if (typeof styleSheet === 'undefined' || styleSheet === null) {
        var styleElement = document.createElement("style");
        styleElement.type = "text/css";
        document.head.appendChild(styleElement);
        styleSheet = styleElement.sheet;
    }

    if (styleSheet) {
        if (styleSheet.insertRule)
            styleSheet.insertRule(selector + ' {' + rules + '}', styleSheet.cssRules.length);
        else if (styleSheet.addRule)
            styleSheet.addRule(selector, rules);
    }
}

use .css in Jquery like $('strong').css('background','red');

$('strong').css('background','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<strong> Example
</strong> 


if you know at least one <style> tag exist in page , use this function :

CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};

usage :

CSS("div{background:#00F}");

참고URL : https://stackoverflow.com/questions/707565/how-do-you-add-css-with-javascript

반응형