Change CSS class properties with jQuery

后端 未结 8 1614
心在旅途
心在旅途 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:35

    You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.

    Dynamically Load CSS from a File

    function updateStyleSheet(filename) {
        newstylesheet = "style_" + filename + ".css";
    
        if ($("#dynamic_css").length == 0) {
            $("head").append("")
            css = $("head").children(":last");
    
            css.attr({
              id: "dynamic_css",
              rel:  "stylesheet",
              type: "text/css",
              href: newstylesheet
            });
        } else {
            $("#dynamic_css").attr("href",newstylesheet);
        }
    }
    

    The example above is copied from:

    • How To Switch CSS Files On-The-Fly Using jQuery

    Dynamically Add a Style Element

    $("head").append('');
    var newStyleElement = $("head").children(':last');
    newStyleElement.html('.red{background:green;}');
    

    The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.

提交回复
热议问题