How to dynamically change a class css styling?

前端 未结 4 557
有刺的猬
有刺的猬 2021-01-05 08:59

Goal

In my program I want to do both things with jquery/javascript:

  1. Change styling of css classes dynamically
  2. Add/remove classes to elements
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-05 09:11

    While other (working) answers have been supplied, they don't actually answer your question - namely, they don't change the specified css class, but instead override it by adding another rule later in the document.

    They achieve this, basically:

    Before

    .someClass
    {
      color: red;
    }
    

    After

    .someClass
    {
      color: red;
    }
    
    .someClass
    {
      color: white;
    }
    

    When in many cases, a better option would see the color attribute of the existing rule altered.

    Well, as it turns out - the browser maintains a collection of style-sheets, style-sheet rules and attributes of said rules. We may prefer instead, to find the existing rule and alter it. (We would certainly prefer a method that performed error checking over the one I present!)

    The first console msg comes from the 1 instance of a #coords rule. The next three come from the 3 instances of the .that rule

    function byId(id){return document.getElementById(id)}
    
    window.addEventListener('load', onDocLoaded, false);
    
    function onDocLoaded(evt)
    {
    	byId('goBtn').addEventListener('click', onGoBtnClicked, false);
    }
    
    function onGoBtnClicked(evt)
    {
    	alterExistingCSSRuleAttrib('#coords', 'background-color', 'blue');
    	alterExistingCSSRuleAttrib('.that', 'color', 'red');
    }
    
    // useful for HtmlCollection, NodeList, String types (array-like types)
    function forEach(array, callback, scope){for (var i=0,n=array.length; i
    #coords
    {
        font-size: 0.75em;
    	width: 10em;
    	background-color: red;
    }
    .that
    {
    	color: blue;
    }
    
    
    
    	
    Test div

提交回复
热议问题