如何使用jQuery / JS检测元素的继承背景颜色? [英] How do I detect the inherited background-color of an element using jQuery/JS?

查看:116
本文介绍了如何使用jQuery / JS检测元素的继承背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery(或只是JavaScript),如何检测元素的继承背景颜色?



例如:

 < div style =background-color:red> 
< p id =target>我想知道这里的背景颜色是红色< / p>
< / div>但是:

 

code> $('#target')。css('background-color')== rgba(0,0,0,0)

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



我要求一个通用解决方案。

解决方案

$('#target')。parent()。css('background-color' div>

这可以通过在循环中使用 parent()来实现,直到到达 body



我已经设置了一个快速的 jsfiddle 网站与一个小演示根据您的代码。



编辑
好​​抓住fudgey。经过一些测试后,IE7会返回'transparent',而不是 rgba(0,0,0,0)值。 这是我在IE7,Chrome 7和Firefox 3.6.1.2中测试的更新链接。使用此方法的另一个警告:Chrome / Firefox将返回 rgb(255,0,0); IE返回'red'


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.

解决方案

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

这篇关于如何使用jQuery / JS检测元素的继承背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆