How to get computed background color style inherited from parent element
我有此HTML页面:
1 2 3 4 | document.addEventListener("DOMContentLoaded", function (event) { var inner_div = document.getElementById("innerDiv"); console.log(getComputedStyle(inner_div, null)["backgroundColor"]); }); |
1 2 3 | #outterDiv { background-color: papayawhip; } |
1 | I am an inner div |
我想找出内部div的计算背景色,而不必研究父元素的计算样式。有可能吗?
您显然是想问
How do I find the background color for some element which is used by virtue of that color being set as the background color of some ancestor which shows through because all intervening elements having transparent background color?
但是,您的问题令人困惑,因为您使用的是"继承"一词,该词在CSS中具有非常具体的含义,在这里与此无关。
内部div看起来像是具有木瓜背景的原因是实际上它具有透明的背景,可以让外部div的木瓜背景显示出来。内部div没有任何东西知道或关心木瓜鞭,也可以查询返回木瓜鞭。
找到内部div将具有木瓜背景的唯一方法是遍历DOM树并找到具有非透明背景色的最接近的父级。在建议作为重复目标的问题中对此进行了解释。
顺便问一下,您的根本问题是什么?你为什么要这样做?可能有更好的方法。
解决方案
下面是一些普通的js,它们将获取给定元素的有效背景色:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | function getInheritedBackgroundColor(el) { // get default style for current browser var defaultStyle = getDefaultBackground() // typically"rgba(0, 0, 0, 0)" // get computed color for el var backgroundColor = window.getComputedStyle(el).backgroundColor // if we got a real value, return it if (backgroundColor != defaultStyle) return backgroundColor // if we've reached the top parent el without getting an explicit color, return default if (!el.parentElement) return defaultStyle // otherwise, recurse and try again on parent element return getInheritedBackgroundColor(el.parentElement) } function getDefaultBackground() { // have to add to the document in order to use getComputedStyle var div = document.createElement("div") document.head.appendChild(div) var bg = window.getComputedStyle(div).backgroundColor document.head.removeChild(div) return bg } |
然后您可以这样称呼它:
1 2 | var myEl = document.getElementById("a") var bgColor = getInheritedBackgroundColor(myEl) |
jsFiddle中的演示
解释
该解决方案通过检查特定元素的解析值来工作。如果背景是透明的,它将从元素的父元素重新开始,直到找到定义的颜色或到达顶部为止。
有两个主要概念需要熟悉:
根据MDN,
这种区别看似微不足道,但重要的是要了解页面上的大多数div可能是透明的。它们不绘制任何颜色,只是不遮罩父元素。如果继承了背景值,则具有透明性的颜色会堆叠并在子元素上变得更浓
根据MDN,解析值是浏览器从
因此
进一步阅读
-
MDN-颜色值
-
MDN-背景颜色
-
MDN-
.getComputedStyle() -
SO-如何获取HTML元素的背景色?
-
SO-获取元素的真实背景色?
-
SO-如何使用JS检测元素的继承背景色?
-
因此-getComputedStyle给出的是"透明"而不是实际的背景颜色
-
SO-如何在JavaScript中获取元素的背景色?
将
1 2 3 4 | document.addEventListener("DOMContentLoaded", function (event) { var inner_div = document.getElementById("innerDiv"); console.log(getComputedStyle(inner_div, null)["backgroundColor"]); }); |
1 2 3 4 5 6 | #outterDiv { background-color: papayawhip; } #innerDiv { background-color: inherit; } |
1 | I am an inner div |