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
485 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 Reply

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'.


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

...