Inherited CSS Values via Javascript

后端 未结 4 2034
半阙折子戏
半阙折子戏 2020-12-06 17:55

On my page I am changing some css styles via javascript. When I try and pull a value that has been inherited - it comes up blank. Consider the following:

            


        
相关标签:
4条回答
  • 2020-12-06 18:20

    You'll want to use getComputedStyle.

    The .style property is a means of accessing and setting inline style (i.e. like the style attribute).

    Note, however, that your example has nothing to do with inheritance. Just rule-sets that apply directly to the elements you are interested in. Inheritance is when an element takes on the same style as its parent via the inherit keyword.

    span {
        color: inherit;
    }
    

    getComputedStyle will give the final computed value though, so it will pick up inherited values too.

    0 讨论(0)
  • 2020-12-06 18:22
    if (!window.getComputedStyle) 
    {
        window.getComputedStyle = function(el, pseudo) 
        {
            this.el = el;
            this.getPropertyValue = function(prop) {
    
            var re = /(\-([a-z]){1})/g;
            if (prop == 'float') 
                prop = 'styleFloat';
            if (re.test(prop)) 
            {
                prop = prop.replace(re, function () {
    
                return arguments[2].toUpperCase();
               });
            }
    
            return el.currentStyle[prop] ? el.currentStyle[prop] : null;
          }
    
          return this;
       }
    }
    
    function GetCompStyle()
    {   
        var compStyle = window.getComputedStyle(document.getElementById('FilterBox'), "");
        alert(compStyle.getPropertyValue("display"));   
    }
    
    0 讨论(0)
  • 2020-12-06 18:30

    Your second CSS rule:

    .Sliding #FilterBox
    {
        height: 185px;
        background-color: Fuchsia;
    }
    

    will match anything with id "FilterBox" that is a descendant of anything with a class "Sliding", so this rule does not apply to your div.

    And to get the computed style, you can refer to Fabien's answer, or consider using jQuery, which makes this stuff a lot easier:

    using jQuery, $("#FilterBox").css("display") would return the current value for "display".

    0 讨论(0)
  • 2020-12-06 18:36

    You need to look at the computed style, see here

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