복붙노트

[JQUERY] 런타임에 jQuery를 가진 CSS 규칙 / 클래스 만들기

JQUERY

런타임에 jQuery를 가진 CSS 규칙 / 클래스 만들기

해결법


  1. 1.당신은 스타일 요소를 생성하고 DOM에 삽입 할 수 있습니다

    당신은 스타일 요소를 생성하고 DOM에 삽입 할 수 있습니다

    $("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head");
    $("<div/>").addClass("redbold").text("SOME NEW TEXT").appendTo("body");
    

    오페라 10 Firefox 3.5 IE 8 IE6 테스트


  2. 2.간단히

    간단히

    $("<style>")
        .prop("type", "text/css")
        .html("\
        #my-window {\
            position: fixed;\
            z-index: 102;\
            display:none;\
            top:50%;\
            left:50%;\
        }")
        .appendTo("head");
    

    백 슬래시 드러내? 그들은 새로운 라인에있는 문자열을 결합하는 데 사용됩니다. 그들을두면 오류가 발생합니다.


  3. 3.당신은 객체에 CSS를 적용 할 수 있습니다. 이처럼 자바 스크립트에서 객체를 정의 할 수 있습니다 :

    당신은 객체에 CSS를 적용 할 수 있습니다. 이처럼 자바 스크립트에서 객체를 정의 할 수 있습니다 :

    var my_css_class = { backgroundColor : 'blue', color : '#fff' };
    

    그리고 단순히 모든 사람에게 당신이 원하는 요소를 적용

    $("#myelement").css(my_css_class);
    

    그래서 다시 사용할 수 있습니다. 어떤 목적이 비록을 위해 할 것인가?


  4. 4.당신이 IE <9를 지원하기 위해 필요하지 않은 경우는 dottoro에있어서, 상기 insertRule를 사용할 수 있습니다. 크로스 브라우저 코드의 비트 거기뿐만 아니라있다.

    당신이 IE <9를 지원하기 위해 필요하지 않은 경우는 dottoro에있어서, 상기 insertRule를 사용할 수 있습니다. 크로스 브라우저 코드의 비트 거기뿐만 아니라있다.

    document.styleSheets[0].insertRule('#my-window {\
        position: fixed;\
        z-index: 102;\
        display:none;\
        top:50%;\
        left:50%;\
    }', 0)
    

  5. 5.여기에있는 JQuery와 플러그인 분사 CSS에 당신을 허용한다 :

    여기에있는 JQuery와 플러그인 분사 CSS에 당신을 허용한다 :

    https://github.com/kajic/jquery-injectCSS

    예:

    $.injectCSS({
        "#my-window": {
            "position": "fixed",
            "z-index": 102,
            "display": "none",
            "top": "50%",
            "left": "50%"
        }
    });
    

  6. 6.이 개념은 여기와 여기에 설명 된 사용하지만, 내가 JSON-스타일 선언의 사용을 확인하고 싶었 이것은 다른 답변의 일부에 비해 아무것도 새로운되지 않습니다 :

    이 개념은 여기와 여기에 설명 된 사용하지만, 내가 JSON-스타일 선언의 사용을 확인하고 싶었 이것은 다른 답변의 일부에 비해 아무것도 새로운되지 않습니다 :

    function addCssRule(rule, css) {
      css = JSON.stringify(css).replace(/"/g, "").replace(/,/g, ";");
      $("<style>").prop("type", "text/css").html(rule + css).appendTo("head");
    }
    

    용법:

    addCssRule(".friend a, .parent a", {
      color: "green",
      "font-size": "20px"
    });
    

    나는 그것이 CSS의 모든 기능을 포함하면 모르겠지만, 지금까지 나를 위해 작동합니다. 그렇지 않은 경우, 그것을 자신의 필요를위한 시작 점을 고려하십시오. :)


  7. 7.당신이 CSS 블록 / 파일에 CSS를 하드 코딩하지 않으려면, 동적 HTML 요소, ID의, 클래스와 CSS를 추가 할 jQuery를 사용할 수 있습니다.

    당신이 CSS 블록 / 파일에 CSS를 하드 코딩하지 않으려면, 동적 HTML 요소, ID의, 클래스와 CSS를 추가 할 jQuery를 사용할 수 있습니다.

    $(document).ready(function() {
      //Build your CSS.
      var body_tag_css = {
        "background-color": "#ddd",
        "font-weight": "",
        "color": "#000"
      }
      //Apply your CSS to the body tag.  You can enter any tag here, as
      //well as ID's and Classes.
      $("body").css(body_tag_css);
    });
    

  8. 8.jQuery를 (). CSS는 () 스타일 시트 규칙을 변경하지 않습니다, 그냥 각각 일치하는 요소의 스타일을 변경합니다.

    jQuery를 (). CSS는 () 스타일 시트 규칙을 변경하지 않습니다, 그냥 각각 일치하는 요소의 스타일을 변경합니다.

    대신에, 여기에 내가 스타일 시트 규칙 자체를 수정하는 데 쓴 자바 스크립트 함수입니다.

        /**
         * Modify an existing stylesheet.
         * - sheetId - the id of the <link> or <style> element that defines the stylesheet to be changed
         * - selector - the id/class/element part of the rule.  e.g. "div", ".sectionTitle", "#chapter2"
         * - property - the CSS attribute to be changed.  e.g. "border", "font-size"
         * - value - the new value for the CSS attribute.  e.g. "2px solid blue", "14px"
         */
        function changeCSS(sheetId, selector, property, value){
            var s = document.getElementById(sheetId).sheet;
            var rules = s.cssRules || s.rules;
            for(var i = rules.length - 1, found = false; i >= 0 && !found; i--){
                var r = rules[i];
                if(r.selectorText == selector){
                    r.style.setProperty(property, value);
                    found = true;
                }
            }
            if(!found){
                s.insertRule(selector + '{' + property + ':' + value + ';}', rules.length);
            }
        }
    

    장점 :

    주의 사항 :

    이 기능에 약간의 개선을 같이 느끼는 경우에, 당신은 몇 가지 유용한 API 문서를 여기에서 찾을 수 있습니다 : https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet


  9. 9.당신이 jQuery를 (예 : 특정 위젯의 기존 jQueryUI의 CSS 프레임 워크를 확장으로) 즉 사용자 정의 CSS를 필요로 위젯을 만들 경우 사용자 정의 규칙을 추가하면 유용합니다. 이 솔루션은 타 라스의 대답 (위의 첫 번째)에 구축합니다.

    당신이 jQuery를 (예 : 특정 위젯의 기존 jQueryUI의 CSS 프레임 워크를 확장으로) 즉 사용자 정의 CSS를 필요로 위젯을 만들 경우 사용자 정의 규칙을 추가하면 유용합니다. 이 솔루션은 타 라스의 대답 (위의 첫 번째)에 구축합니다.

    당신의 HTML 마크 업을 가정하면 "addrule"와 "대상"텍스트를 포함하는 ID로 DIV의 ID와 버튼이 있습니다 :

    jQuery 코드 :

    $( "#addrule" ).click(function () { addcssrule($("#target")); });
    
    function addcssrule(target) 
    { 
    var cssrules =  $("<style type='text/css'> </style>").appendTo("head");
    
    cssrules.append(".redbold{ color:#f00; font-weight:bold;}"); 
    cssrules.append(".newfont {font-family: arial;}"); 
    target.addClass("redbold newfont");     
    }       
    

    이 방법의 장점은 마음대로 규칙을 추가하거나 뺄 코드에서 변수 cssrules를 다시 사용할 수 있다는 것입니다. cssrules는 같은 당신이 작업에 지속적으로 지역 변수가 위젯 JQuery와 같은 영구 객체에 포함됩니다.


  10. 10.예를 들어, - 자주 동적으로 변화 스타일에 수 있어야합니다 (특별한)의 경우 테마 빌더 응용 프로그램 - CSSStyleSheet.insertRule를 (<스타일> 태그를 추가하거나 호출은) 성능을 디버깅 의미를 설계 할 수있는 성장 스타일 시트가 발생합니다.

    예를 들어, - 자주 동적으로 변화 스타일에 수 있어야합니다 (특별한)의 경우 테마 빌더 응용 프로그램 - CSSStyleSheet.insertRule를 (<스타일> 태그를 추가하거나 호출은) 성능을 디버깅 의미를 설계 할 수있는 성장 스타일 시트가 발생합니다.

    나의 접근 방식은 어떤 규칙을 설정하는 방법에 대한 기존을 삭제, 선택 / 속성 콤보 당 하나의 규칙을 할 수 있습니다. API는 간단하고 유연합니다 :

    function addStyle(selector, rulename, value) {
        var stylesheet = getAppStylesheet();
        var cssRules = stylesheet.cssRules || stylesheet.rules;
        var rule = stylesheet.insertRule(selector + ' { ' + rulename + ':' + value + ';}', cssRules.length);
    }
    
    function clearStyle(selector, rulename) {
        var stylesheet = getAppStylesheet();
        var cssRules = stylesheet.cssRules || stylesheet.rules;
        for (var i=0; i<cssRules.length; i++) {
            var rule = cssRules[i];
            if (rule.selectorText == selector && rule.style[0] == rulename) {
                stylesheet.deleteRule(i);
                break;
            }
        }       
    }
    
    function addStyles(selector, rules) {
        var stylesheet = getAppStylesheet();
        var cssRules = stylesheet.cssRules || stylesheet.rules;
        for (var prop in rules) {
            addStyle(selector, prop, rules[prop]);
        }
    }
    
    function getAppStylesheet() {
        var stylesheet = document.getElementById('my-styles');
        if (!stylesheet) {
            stylesheet = $('<style id="my-styles">').appendTo('head')[0];
        }
        stylesheet = stylesheet.sheet;
        return stylesheet;
    }
    

    용법:

    addStyles('body', {
        'background-color': 'black',
        color: 'green',
        margin: 'auto'
    });
    
    clearStyle('body', 'background-color');
    addStyle('body', 'color', '#333')
    

  11. 11.당신이 동적 페이지에