Change CSS class properties with jQuery

后端 未结 8 1554
心在旅途
心在旅途 2020-11-29 04:59

Is there a way to change the properties of a CSS class, not the element properties, using jQuery?

This is a practical example:

I have a div with class

相关标签:
8条回答
  • 2020-11-29 05:41

    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

    0 讨论(0)
  • 2020-11-29 05:42

    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");
    }
    
    0 讨论(0)
提交回复
热议问题