简体   繁体   中英

Get (background) color of HTML page of some top element

First of all, document.body.style.backgroundColor does not return the right color in my case (it isn't even set), because the page is all filled with divs.

Is there some way to get the color of some pixels in the top pixel row? Or some other generic way to get some background color of some top (or dominating) element? The solution doesn't have to be exact, only mostly working (esp for my cases :)).

One method, which kinda works ok for my current case, is this:

$("div").css("background-color")

However, I'm not fully happy with it, as it makes too much exceptions, like it needs JQuery, and expects that this returns a related div, and that div has a background color set.

Something like this should find the first child element of the body with a background color.
Note that it does not search for nested elements.

var el = document.querySelector('body > *'), color = null;

while ( el && !color) {
    color = el && el.style ? el.style.backgroundColor : null;
    el = el.nextSibling;
}

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM