developer tip

jQuery로 CSS 클래스 속성 변경

copycodes 2020. 11. 25. 08:06
반응형

jQuery로 CSS 클래스 속성 변경


jQuery를 사용하여 요소 속성이 아닌 CSS 클래스의 속성을 변경하는 방법이 있습니까?

이것은 실용적인 예입니다.

클래스가있는 div가 있습니다. red

.red {background: red;}

red클래스 red배경이 할당 된 요소가 아닌 클래스 배경 속성 을 변경하고 싶습니다 .

jQuery .css () 메서드로 수행하면 :

$('.red').css('background','green');

현재 클래스가있는 요소에 영향을 미칩니다 red. 여기까지 모든 것이 좋습니다. 그러나 Ajax 호출을하고 red클래스 와 함께 더 많은 div를 삽입 하면 녹색 배경이없고 초기 red배경이됩니다.

jQuery .css () 메서드를 다시 호출 할 수 있습니다. 하지만 수업 자체를 바꿀 수있는 방법이 있는지 알고 싶습니다. 이것은 단지 기본적인 예라고 생각하십시오.


jQuery를 사용하여 CSS 속성을 직접 변경할 수 없습니다. 그러나 최소한 두 가지 방법으로 동일한 효과를 얻을 수 있습니다.

파일에서 동적으로 CSS로드

function updateStyleSheet(filename) {
    newstylesheet = "style_" + filename + ".css";

    if ($("#dynamic_css").length == 0) {
        $("head").append("<link>")
        css = $("head").children(":last");

        css.attr({
          id: "dynamic_css",
          rel:  "stylesheet",
          type: "text/css",
          href: newstylesheet
        });
    } else {
        $("#dynamic_css").attr("href",newstylesheet);
    }
}

위의 예는 다음에서 복사되었습니다.

스타일 요소를 동적으로 추가

$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');

예제 코드는 원래 Alvaro 가 주석에서 참조한 이 JSFiddle 바이올린 에서 복사되었습니다 .


동적으로로드하여 다른 스타일 시트를 사용할 수없는 경우이 함수를 사용하여 CSS 클래스를 수정할 수 있습니다. 도움이 되었기를 바랍니다 ...

function changeCss(className, classValue) {
    // we need invisible container to store additional css definitions
    var cssMainContainer = $('#css-modifier-container');
    if (cssMainContainer.length == 0) {
        var cssMainContainer = $('<div id="css-modifier-container"></div>');
        cssMainContainer.hide();
        cssMainContainer.appendTo($('body'));
    }

    // and we need one div for each class
    classContainer = cssMainContainer.find('div[data-class="' + className + '"]');
    if (classContainer.length == 0) {
        classContainer = $('<div data-class="' + className + '"></div>');
        classContainer.appendTo(cssMainContainer);
    }

    // append additional style
    classContainer.html('<style>' + className + ' {' + classValue + '}</style>');
}

이 함수는 모든 클래스 이름을 취하고 이전에 설정 한 값을 새 값으로 바꿉니다. classValue :에 다음을 전달하여 여러 값을 추가 할 수 있습니다 "background: blue; color:yellow".


원하는 답을 찾지 못해서 직접 해결했습니다.
컨테이너 div를 수정하세요!

<div class="rotation"> <!-- Set the container div's css -->
  <div class="content" id='content-1'>This div gets scaled on hover</div>
</div>

<!-- Since there is no parent here the transform doesnt have specificity! -->
<div class="rotation content" id='content-2'>This div does not</div>

css you want to persist after executing $target.css()

.content:hover {
    transform: scale(1.5);
}

modify content's containing div with css()

$(".rotation").css("transform", "rotate(" + degrees + "deg)");

Codepen example


You can remove classes and add classes dynamically

$(document).ready(function(){
    $('#div').removeClass('left').addClass('right');
});

$(document)[0].styleSheets[styleSheetIndex].insertRule(rule, lineIndex);


styleSheetIndex is the index value that corresponds to which order you loaded the file in the <head> (e.g. 0 is the first file, 1 is the next, etc. if there is only one CSS file, use 0).

rule is a text string CSS rule. Like this: "body { display:none; }".

lineIndex is the line number in that file. To get the last line number, use $(document)[0].styleSheets[styleSheetIndex].cssRules.length. Just console.log that styleSheet object, it's got some interesting properties/methods.

Because CSS is a "cascade", whatever rule you're trying to insert for that selector you can just append to the bottom of the CSS file and it will overwrite anything that was styled at page load.

In some browsers, after manipulating the CSS file, you have to force CSS to "redraw" by calling some pointless method in DOM JS like document.offsetHeight (it's abstracted up as a DOM property, not method, so don't use "()") -- simply adding that after your CSSOM manipulation forces the page to redraw in older browsers.


So here's an example:

var stylesheet = $(document)[0].styleSheets[0]; stylesheet.insertRule('body { display:none; }', stylesheet.cssRules.length);


You can add a class to the parent of the red div, e.g. green-style

$('.red').parent().addClass('green-style');

then add style to the css

.green-style .red {
     background:green; 
}

so everytime you add red element under green-style, the background will be green


Here's a bit of an improvement on the excellent answer provided by Mathew Wolf. This one appends the main container as a style tag to the head element and appends each new class to that style tag. a little more concise and I find it works well.

function changeCss(className, classValue) {
    var cssMainContainer = $('#css-modifier-container');

    if (cssMainContainer.length == 0) {
        var cssMainContainer = $('<style id="css-modifier-container"></style>');
        cssMainContainer.appendTo($('head'));
    }

    cssMainContainer.append(className + " {" + classValue + "}\n");
}

You may want to take a different approach: Instead of changing the css dynamically, predefine your styles in CSS the way you want them. Then use JQuery to add and remove styles from within Javascript. (see code from Ajmal)

참고URL : https://stackoverflow.com/questions/11474430/change-css-class-properties-with-jquery

반응형