jQuery CSS: Dynamically change attributes of a class

后端 未结 7 1957
悲哀的现实
悲哀的现实 2020-12-09 08:33

I want to change the attribute of a class on which all element that use the class for the rest of the web application life (from start of use until the user exits the web ap

相关标签:
7条回答
  • 2020-12-09 08:59

    I would do something like below. It does not modify class, but it does what you need.

    $("body").addClass("updatedClass");
    $("p").last().after("<div class='myClass'>Now!</div>");
    

    and css:

    .myClass{
        background-color: #ffff00;    
    }
    .updatedClass .myClass {
        background-color: #00FFFF;    
    }
    

    Demo

    In any case, if you want to keep this enabled for any page, you should do this with server being involved. For instance, by setting some variable into a session and than returning corresponding css based on that variable.

    Or you can use cookies (check jquery cookies plugin for simpler access to cookies on client side) and modify class with inserting style tag or by adding corresponding class to body in jQuery.ready callback.

    for instance, with cookies (using plugin mentioned above) code could be like this:

    $("body").addClass("updatedClass");
    $("p").last().after("<div class='myClass'>Now!</div>");
    $.cookie('baseClass', 'updatedClass'); // set class for current session (this cookie will be deleted after user ends his session)
    

    and than, each page should have:

    $(function() {
       if($.cookie('baseClass') != null) {
            $("body").addClass($.cookie('baseClass'));// or style tag could be added here instead.
       }
    })
    
    0 讨论(0)
提交回复
热议问题