目前我想获取指定对象的真实背景颜色,在这里,真实的意思是人们看到的,例如,给定以下代码:
<div id="foo" style="background-color: red">
I am red
<span id="bar">
I have no background, but I am red
</span>
</div>
的真实背景颜色#bar
应该是rbg(255,0,0)
.
这是我到目前为止所拥有的:
function color_visible(color_str) {
return color_str && !(color_str.substr(0, 4) == "rgba" && color_str.substr(-2, 2) == "0)");
}
function get_bgcolor (obj) {
var ret = $(obj).css("background-color");
if (!color_visible(ret)) ret = $(obj).css("bgcolor");
if (color_visible(ret)) return ret;
if (!$(obj).is("body")) return get_bgcolor($(obj).parent());
return "rgb(255, 255, 255)";
}
但是有没有更好的方法呢?
Stack Snippet 和jsFiddle中的演示
function color_visible(color_str) {
return color_str && !(color_str.substr(0, 4) == "rgba" && color_str.substr(-2, 2) == "0)");
}
function get_bgcolor (obj) {
var ret = $(obj).css("background-color");
if (!color_visible(ret)) ret = $(obj).css("bgcolor");
if (color_visible(ret)) return ret;
if (!$(obj).is("body")) return get_bgcolor($(obj).parent());
return "rgb(255, 255, 255)";
}
console.log(get_bgcolor($("#bar")));
console.log(get_bgcolor($("#baz")));
console.log(get_bgcolor($("#foo")));
console.log(get_bgcolor($("body")));
body {
background-color: yellow;
}
.bg_white {
background-color: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div id="foo" style="background-color: red">
I am red
<span id="bar">
I have no background
</span>
<span id="baz" class="bg_white">
I am white
</span>
</div>
I am yellow
</div>