How can I tell if a particular CSS property is inherited with jQuery?

后端 未结 7 831
自闭症患者
自闭症患者 2020-11-29 03:49

This is a very simple question, so I\'ll keep it really brief:

How can I tell if a particular DOM element\'s CSS property is inherited?

Reas

7条回答
  •  没有蜡笔的小新
    2020-11-29 04:36

    To actually determine whether a css style was inherited or set on the element itself, you would have to implement the exact rules that the browsers apply to determine the used value for a particular style on an element.

    You would have to implement this spec that specifies how the computed and used values are calculated.

    CSS selectors may not always follow a parent-child relationship which could have simplified matters. Consider this CSS.

    body {
        color: red;
    }
    
    div + div {
        color: red;
    }
    

    and the following HTML:

    
        
    first
    second

    Both first and second wil show up in red, however, the first div is red because it inherits it from the parent. The second div is red because the div + div CSS rule applies to it, which is more specific. Looking at the parent, we would see it has the same color, but that's not where the second div is getting it from.

    Browsers don't expose any of the internal calculations, except the getComputedStyle interface.

    A simple, but flawed solution would be to run through each selector from the stylesheets, and check if a given element satisfies the selector. If yes, then assume that style was applied directly on the element. Say you wanted to go through each style in the first stylesheet,

    var myElement = $('..');
    var rules = document.styleSheets[0].cssRules;
    for(var i = 0; i < rules.length; i++) {
        if (myElement.is(rules[i].selectorText)) {
            console.log('style was directly applied to the element');
        }
    }
    

提交回复
热议问题