Changing CSS Values with Javascript

后端 未结 9 1411
借酒劲吻你
借酒劲吻你 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");

    0 讨论(0)
  • 2020-11-22 17:41

    I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.

    style=document.createElement('style');
    document.head.appendChild(style);
    stylesheet=style.sheet;
    function css(selector,property,value)
    {
        try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
        catch(err){}
    }
    

    Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.

    0 讨论(0)
  • 2020-11-22 17:44

    You can get the "computed" styles of any element.

    IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".

    You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).

    That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.

    The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value)

    Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:

    <div style="width:50%">....</div>
    
    0 讨论(0)
  • 2020-11-22 17:45

    Perhaps try this:

    function CCSStylesheetRuleStyle(stylesheet, selectorText, style, 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
    }
    
    0 讨论(0)
  • 2020-11-22 17:48

    I've never seen any practical use of this, but you should probably consider DOM stylesheets. However, I honestly think that's overkill.

    If you simply want to get the width and height of an element, irrespective of where the dimensions are being applied from, just use element.offsetWidth and element.offsetHeight.

    0 讨论(0)
  • 2020-11-22 17:54

    Please! Just ask w3 (http://www.quirksmode.org/dom/w3c_css.html)! Or actually, it took me five hours... but here it is!

    function css(selector, property, value) {
        for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles
            //Try add rule
            try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);
            } catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE
        }
    }
    

    The function is really easy to use.. example:

    <div id="box" class="boxes" onclick="css('#box', 'color', 'red')">Click Me!</div>
    Or:
    <div class="boxes" onmouseover="css('.boxes', 'color', 'green')">Mouseover Me!</div>
    Or:
    <div class="boxes" onclick="css('body', 'border', '1px solid #3cc')">Click Me!</div>
    

    Oh..


    EDIT: as @user21820 described in its answer, it might be a bit unnecessary to change all stylesheets on the page. The following script works with IE5.5 as well as latest Google Chrome, and adds only the above described css() function.

    (function (scope) {
        // Create a new stylesheet in the bottom
        // of <head>, where the css rules will go
        var style = document.createElement('style');
        document.head.appendChild(style);
        var stylesheet = style.sheet;
        scope.css = function (selector, property, value) {
            // Append the rule (Major browsers)
            try { stylesheet.insertRule(selector+' {'+property+':'+value+'}', stylesheet.cssRules.length);
            } catch(err) {try { stylesheet.addRule(selector, property+':'+value); // (pre IE9)
            } catch(err) {console.log("Couldn't add style");}} // (alien browsers)
        }
    })(window);
    
    0 讨论(0)
提交回复
热议问题