programing

jQuery를 사용하여 CSS 클래스 속성 변경

linuxpc 2023. 4. 1. 08:32
반응형

jQuery를 사용하여 CSS 클래스 속성 변경

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

다음은 실제적인 예입니다.

나는 클래스가 있는 점을 가지고 있다.red

.red {background: red;}

나는 수업을 바꾸고 싶다red클래스가 있는 요소가 아닌 백그라운드 속성red백그라운드가 할당되어 있습니다.

jQuery .css() 메서드로 실행하는 경우:

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

그것은 지금 계급이 있는 요소들에 영향을 미칠 것이다.red여기까지는 괜찮습니다.하지만 만약 내가 에이잭스에 전화를 걸면, 그리고 더 많은 divs를 삽입하면red녹색 배경이 아니라 첫 번째가 될 것입니다.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".

클래스를 제거하고 동적으로 클래스를 추가할 수 있습니다.

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

내가 원하는 답을 찾지 못했기 때문에 내가 직접 해결했다.
container 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 $target.css() 실행 후 유지하다

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

css()를 사용하여 div를 포함하는 콘텐츠 수정

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

코드펜의 예

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


styleSheetIndex파일을 로드한 순서에 대응하는 인덱스 값입니다.<head>(예: 0은 첫 번째 파일, 1은 다음 파일 등) CSS 파일이 하나만 있는 경우 0을 사용합니다.

rule는 텍스트 문자열 CSS 규칙입니다.다음과 같이 합니다."body { display:none; }".

lineIndex는, 그 파일의 회선 번호입니다.마지막 줄 번호를 얻으려면$(document)[0].styleSheets[styleSheetIndex].cssRules.length.그저.console.log그 문체시트 객체에는 몇 가지 흥미로운 특성이나 방법이 있습니다.

CSS는 "캐스케이드"이기 때문에 셀렉터에 삽입하려는 규칙이 무엇이든 CSS 파일 하단에 추가하면 페이지 로드 시 스타일링된 모든 규칙을 덮어쓸 수 있습니다.

한 후 내의 하여 CSS를 를 들어 DOM JS의 CSS를 호출합니다.document.offsetHeight(메서드가 아닌 DOM 속성으로 추상화되므로 ()를 사용하지 마십시오.) 단순히 CSSOM 조작 후 오래된 브라우저에서 페이지가 강제로 다시 그려집니다.


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

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

빨간색 div의 부모에 클래스를 추가할 수 있습니다(예: 녹색 스타일).

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

그런 다음 스타일을 css에 추가합니다.

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

따라서 녹색 스타일 아래에 빨간색 요소를 추가할 때마다 배경이 녹색이 됩니다.

Mathew Wolf가 제공한 훌륭한 답변에 대한 약간의 개선 사항이 있습니다.이것은 헤드 요소에 메인 컨테이너를 스타일 태그로 추가하고 각각의 새로운 클래스를 스타일 태그에 추가합니다.조금 더 간결하고 잘 작동합니다.

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

다른 방법을 사용할 수도 있습니다.CSS를 동적으로 변경하는 대신 원하는 방식으로 CSS에서 스타일을 미리 정의합니다.그런 다음 JQuery를 사용하여 Javascript 내에서 스타일을 추가 및 삭제합니다.(Ajmal 코드 참조)

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

반응형