简体   繁体   English

得到一些顶级元素的HTML页面的(背景)颜色

[英]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. 首先, document.body.style.backgroundColor在我的情况下不返回正确的颜色(它甚至没有设置),因为页面都填充了div。

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. 但是,我对它并不十分满意,因为它有太多的例外,比如它需要JQuery,并期望这会返回一个相关的div,并且div有一个背景颜色集。

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 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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