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:
<body>
<div>first</div>
<div>second</div>
</body>
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');
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…