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
144 views
in Technique[技术] by (71.8m points)

javascript - Getting the real background-color of an element?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Javascript only version:

function realBackgroundColor(elem) {
    var transparent = 'rgba(0, 0, 0, 0)';
    var transparentIE11 = 'transparent';
    if (!elem) return transparent;

    var bg = getComputedStyle(elem).backgroundColor;
    if (bg === transparent || bg === transparentIE11) {
        return realBackgroundColor(elem.parentElement);
    } else {
        return bg;
    }
}
realBackgroundColor(document.querySelector('#element'));

http://jsfiddle.net/qnLwsr7y/

Note that it does not take opacity or background images into account.


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

...