Currently I want to get the real background-color of a specified object, here, the real means what the people see, for instance, given the following code:
<div id="foo" style="background-color: red">
I am red
<span id="bar">
I have no background, but I am red
</span>
</div>
The real background-color of #bar
should be rbg(255,0,0)
.
Here's what I have so far:
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)";
}
But is there a better way to do it?
Demo in Stack Snippet and 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>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…