Get a CSS value with JavaScript

前端 未结 9 1446
温柔的废话
温柔的废话 2020-11-21 07:55

I know I can set a CSS value through JavaScript such as:

document.getElementById(\'image_1\').style.top = \'100px\';

But, can I

相关标签:
9条回答
  • 2020-11-21 08:15

    As a matter of safety, you may wish to check that the element exists before you attempt to read from it. If it doesn't exist, your code will throw an exception, which will stop execution on the rest of your JavaScript and potentially display an error message to the user -- not good. You want to be able to fail gracefully.

    var height, width, top, margin, item;
    item = document.getElementById( "image_1" );
    if( item ) {
      height = item.style.height;
      width = item.style.width;
      top = item.style.top;
      margin = item.style.margin;
    } else {
      // Fail gracefully here
    }
    
    0 讨论(0)
  • 2020-11-21 08:21

    Cross-browser solution to checking CSS values without DOM manipulation:

    function get_style_rule_value(selector, style)
    {
     for (var i = 0; i < document.styleSheets.length; i++)
     {
      var mysheet = document.styleSheets[i];
      var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
    
      for (var j = 0; j < myrules.length; j++)
      {
       if (myrules[j].selectorText && myrules[j].selectorText.toLowerCase() === selector)
       {
        return myrules[j].style[style];
       }
      }
     }
    };
    

    Usage:

    get_style_rule_value('.chart-color', 'backgroundColor')
    

    Sanitized version (forces selector input to lowercase, and allows for use case without leading ".")

    function get_style_rule_value(selector, style)
    {
     var selector_compare=selector.toLowerCase();
     var selector_compare2= selector_compare.substr(0,1)==='.' ?  selector_compare.substr(1) : '.'+selector_compare;
    
     for (var i = 0; i < document.styleSheets.length; i++)
     {
      var mysheet = document.styleSheets[i];
      var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
    
      for (var j = 0; j < myrules.length; j++)
      {
        if (myrules[j].selectorText)
        {
         var check = myrules[j].selectorText.toLowerCase();
         switch (check)
         {
          case selector_compare  :
          case selector_compare2 : return myrules[j].style[style];
         }
        }
       }
      }
     }
    
    0 讨论(0)
  • 2020-11-21 08:22

    If you're into libraries, why not MyLibrary and getStyle.

    The jQuery css method is misnamed, CSS is just one way of setting styles and doesn't necessarily represent the actual values of an element's style properties.

    0 讨论(0)
提交回复
热议问题