最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get the document's background color - Stack Overflow

programmeradmin3浏览0评论

Most web browsers, by default, render pages as having a white background. However, this is to some extent user customizable, and some browsers are different. So, I want to find a way, either through CSS or JavaScript, to find out the background color of the page. The documentation on Mozilla's website suggests that document.bgColor can be used, and that its default value is white. It also suggests to not use it, since it's deprecated. But the docs seem to be in conflict with observed behavior: document.bgColor is an empty string if the page has no CSS to change it. The alternatives suggested don't work either: everything I tried gives me either an empty string or "transparent", which is clearly wrong: I can not see the desktop beneath my browser, hence it is not transparent. (Incidentally, IE11 actually behaves like Mozilla's documentation says that Firefox does. Go figure.)

I want to create an html list element (<ul>) whose background color matches the background color of the document. Is this possible? (I suppose you might be tempted to ask: if I want it to match the background, isn't "transparent" what I want? No. I want it to cover up some other element. Why? Because I'm making one of those auto-suggest thingies.)

Edit: 2 people have wisely suggested that I add an example so it becomes clear what on earth I'm talking about. Based on the answers I've been receiving, these 2 people are absolutely right. I've added a link to a fiddle in the comments of one of the answers, and now I'm adding it here:

/

Most web browsers, by default, render pages as having a white background. However, this is to some extent user customizable, and some browsers are different. So, I want to find a way, either through CSS or JavaScript, to find out the background color of the page. The documentation on Mozilla's website suggests that document.bgColor can be used, and that its default value is white. It also suggests to not use it, since it's deprecated. But the docs seem to be in conflict with observed behavior: document.bgColor is an empty string if the page has no CSS to change it. The alternatives suggested don't work either: everything I tried gives me either an empty string or "transparent", which is clearly wrong: I can not see the desktop beneath my browser, hence it is not transparent. (Incidentally, IE11 actually behaves like Mozilla's documentation says that Firefox does. Go figure.)

I want to create an html list element (<ul>) whose background color matches the background color of the document. Is this possible? (I suppose you might be tempted to ask: if I want it to match the background, isn't "transparent" what I want? No. I want it to cover up some other element. Why? Because I'm making one of those auto-suggest thingies.)

Edit: 2 people have wisely suggested that I add an example so it becomes clear what on earth I'm talking about. Based on the answers I've been receiving, these 2 people are absolutely right. I've added a link to a fiddle in the comments of one of the answers, and now I'm adding it here:

https://jsfiddle.net/ftgu97fj/5/

Share Improve this question edited Sep 17, 2016 at 8:48 Jan Turoň 32.9k23 gold badges137 silver badges177 bronze badges asked Sep 17, 2016 at 5:33 Mark VYMark VY 1,67117 silver badges36 bronze badges 16
  • useallfive.com/thoughts/… – Hitmands Commented Sep 17, 2016 at 5:41
  • this seems to be solving a different problem? – Mark VY Commented Sep 17, 2016 at 5:45
  • 2 On an empty page in Chrome: window.getComputedStyle(document.body)["background-color"] "rgba(0, 0, 0, 0)" – Larkeith Commented Sep 17, 2016 at 6:00
  • 1 @guest271314 the goal is to identify the background color for a page where it has not been set; that is, the default background color of the browser the client is using. – Larkeith Commented Sep 17, 2016 at 6:02
  • 2 People could write hypothetical answers to a hypothetical question all day long - it certainly keeps the electricity companies happy. As a better and more usual alternative however, you could simply include the markup you're using and turn this into a concrete problem. – enhzflep Commented Sep 17, 2016 at 6:40
 |  Show 11 more comments

6 Answers 6

Reset to default 10

In the late bronze age, you could use CSS2 system colors.

Later, they were deprecated (but are still well supported to these days) because of the concept of CSS3 appearance property.

Later, the standards abandoned the appearance property (except for auto and none, browsers don't support other values) and system colors were brought back to life with different names, see CSS4 system colors Please upvote Michael Allan's answer below as he mentioned it earlier.

So the solution is:

ul { background-color: Window; } /* Window background in CSS2, deprecated */

ul { background-color: Canvas; } /* Document background in CSS4 */

EDIT: Jan Turoň has found a method of doing this using CSS2 System Colors; Please defer to his answer. Note that the system colors are deprecated and that window is the default background color.

Based on the answer in this post regarding background color of highlighted text, it seems that this is likely not possible; the relevant question is also a browser-specific choice of a very similar nature:

Kaiido:

I would say that you can't.

Both getComputedStyle(yourElement, '::selection').backgroundColor and getComputedStyle(yourElement, '::-moz-selection').backgroundColor will return transparent as default value and browser won't override os's default. (Worth to be mentioned that if you set it to transparent, default os' value will be overriden).

I don't think browsers have access to os default preferences, and if they do, they probably won't let any website access it it so easily.

This question suggests using a canvas element to sample the pixel color, but this unfortunately does not seem to work; in Chrome, it will return 0,0,0,0 for the color of an unset pixel. It gives a potential solution using chrome.tabs, but this is only available to chrome extensions.

The only possibility I can think of would be to use something like HTML2Canvas to "screenshot" the page and sample an empty pixel there, but there is no guarantee this library will operate properly for an unset background.

Nowadays, with access to the system colours and other user preferences, we can simply do this:

    ul { background-color: Canvas }

See: CSS Color Module § System Colors

If <ul> element is a direct descendant of <body> element you can use css inherit keyword

  ul {
    background-color: inherit;
  }

Since comments are getting way too long on OPs post, here's what I'd suggest you try:

window.getComputedStyle(document.body)['backgroundColor'])

The usecase of your autosuggest displaying correctly on pages where no background-color has been set (such as empty page) should be covered by setting white as the default background color for your ul. It becomes alot more problematic if you want to take possible background-images into account as well.

Please also be aware that html can have a background-color as well, and body may be limited in size to not cover the whole viewport. See this pen:

http://codepen.io/connexo/pen/jrAxAZ

This also illustrates that your expectation to see your desktop behind your browser if the body were truly tranparent is wrong.

This will definitely solve the problem! check how the js function works

function getBackground(jqueryElement) {
    // Is current element's background color set?
    var color = jqueryElement.css("background-color");
    
    if (color !== 'rgba(0, 0, 0, 0)') {
        // if so then return that color
        return color;
    }

    // if not: are you at the body element?
    if (jqueryElement.is("body")) {
        // return known 'false' value
        return false;
    } else {
        // call getBackground with parent item
        return getBackground(jqueryElement.parent());
    }
}

$(function() {
    alert(getBackground($("#target")));
    document.getElementById("ul").style.backgroundColor = getBackground($("#target"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<ul id= "ul" style="background-color: red">
    <p id="target">I'd like to know that the background-color here is red</p>
</ul>

i kept the prompt for your better understanding

发布评论

评论列表(0)

  1. 暂无评论