需求场景:
<div id="myDiv1" style="width: 300px;height:100px;display: none;background: #ff0000">红色</div>
<div id="myDiv2" style="width: 300px;height:100px;display: none;background: #00ff00">绿色</div>
<div id="myDiv2" style="width: 300px;height:100px;display: none;background: #00ff00">蓝色</div>
找到颜色是#00ff00的div,并让之显示。
第一种:遍历
$('body').find('*').each(function(){
var style = $(this).attr('style');
if(style.indexOf('0, 255, 0')>=0){
$(this).show();
}
第二种:使用filter,可以写很复杂的选择条件
$('div').filter(function(){
return $(this).attr('style').indexOf('0, 255, 0')>=0;
}).show();
第三种:最简单
$("[style*='00ff00']").show();
但是:我们看到前两种方法必须把#00ff00写成'0,255,0',为什么呢?先看看jjquery把#00ff00自动转换成啥样子了:
alert($("[style*='00ff00']").css('background-color'));
低版本IE中是以HEX格式显示#00ff00,而Chrome、Firefox中则是以GRB格式显示rgb(0, 255, 0),注意数字和逗号之间还有空格!
如果想统一一下,把rgb转换成hex颜色格式即可。十六进制的转换这里就不赘述了。