Changing CSS Values with Javascript

后端 未结 9 1513
借酒劲吻你
借酒劲吻你 2020-11-22 17:16

It\'s easy to set inline CSS values with javascript. If I want to change the width and I have html like this:

<
9条回答
  •  没有蜡笔的小新
    2020-11-22 17:41

    Gathering the code in the answers, I wrote this function that seems running well on my FF 25.

    function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
      /* returns the value of the element style of the rule in the stylesheet
      *  If no value is given, reads the value
      *  If value is given, the value is changed and returned
      *  If '' (empty string) is given, erases the value.
      *  The browser will apply the default one
      *
      * string stylesheet: part of the .css name to be recognized, e.g. 'default'
      * string selectorText: css selector, e.g. '#myId', '.myClass', 'thead td'
      * string style: camelCase element style, e.g. 'fontSize'
      * string value optionnal : the new value
      */
      var CCSstyle = undefined, rules;
      for(var m in document.styleSheets){
        if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
         rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
         for(var n in rules){
           if(rules[n].selectorText == selectorText){
             CCSstyle = rules[n].style;
             break;
           }
         }
         break;
        }
      }
      if(value == undefined)
        return CCSstyle[style]
      else
        return CCSstyle[style] = value
    }
    

    This is a way to put values in the css that will be used in JS even if not understood by the browser. e.g. maxHeight for a tbody in a scrolled table.

    Call :

    CCSStylesheetRuleStyle('default', "#mydiv", "height");

    CCSStylesheetRuleStyle('default', "#mydiv", "color", "#EEE");

提交回复
热议问题