Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How do I detect the inherited background-color of an element using jQuery/JS?

Using jQuery (or just JavaScript), how do I detect the inherited background-color of an element?

For example:

<div style="background-color: red">
    <p id="target">I'd like to know that the background-color here is red</p>
</div>

However:

$('#target').css('background-color') == rgba(0,0,0,0)

and

$('#target').css('backgroundColor') == rgba(0,0,0,0)

I'm asking for a general solution. $('#target').parent().css('background-color') would work in this instance, but not all.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This could be accomplished by using the parent() in a loop until you reach the body tag:

I've set up a quick jsfiddle site with a little demo based on your code.

Edit: Good catch fudgey. After doing some testing it appears that IE7 will return 'transparent' instead of the rgba(0,0,0,0) value. Here's an updated link which I tested in IE7, Chrome 7, and Firefox 3.6.1.2. Another caveat with this approach: Chrome/Firefox will return rgb(255,0,0); IE returned 'red'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...