Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

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

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?

Reason why I'm asking is because with jQuery's css method it will return the computed style, which inherits the parent object's CSS properties. Is there a way to retrieve the properties set on the object itself?

An example might explain what I'm getting at a bit better:

CSS:

div#container {
  color:#fff;
}

HTML:

<div id="container">
  Something that should be interesting
  <div class="black">
    Some other thing that should be interesting
  </div>
</div>

So, in the instance of div.black, which inherits color, how can I tell if it is inherited?

$('div.black:eq(0)').css('color') will obviously give me #fff, but I want to retrieve the style of the element itself, not its parents.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...