如何获取从父元素继承的计算背景颜色样式 [英] How to get computed background color style inherited from parent element

查看:200
本文介绍了如何获取从父元素继承的计算背景颜色样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个HTML页面:



  document.addEventListener(DOMContentLoaded ,function(event){var inner_div = document.getElementById(innerDiv); console.log(getComputedStyle(inner_div,null)[backgroundColor]);});  

  #outterDiv {background-color:papayawhip;}  

 < div id =outterDiv> < div id =innerDiv>我是内部div< / div>< / div>  



我想找出内部div的计算背景颜色,而不必查看parent(s)元素的计算样式。这可能吗?

解决方案

你显然想问


如何找到某种元素的背景颜色,因为该颜色被设置为某些祖先的背景颜色,因为所有干预元素都具有透明的背景颜色?


但是,你的问题很混乱,因为你使用的是inherited这个词,它在CSS中具有非常特殊的含义,这里没有关系。 / p>

CSS意义上继承的 c> c>属性。每个元素都有自己的背景颜色,默认情况下为 transparent



你内在的div 看起来就像它有一个papayawhip背景的原因是它实际上它有一个透明的背景,这让我们的papayawhip背景外部的div显示出来。没有任何关于知道或关心木瓜病的内部div,或者可以被查询以回归木瓜病。



找到内部div将具有papayawhip背景的唯一方法是遍历DOM树并找到具有不透明背景颜色的最近父级。在提议作为重复目标的问题中解释了这一点。



顺便问一下,你的根本问题是什么?你为什么要这样做?可能有更好的方法。


I have this HTML page:

document.addEventListener("DOMContentLoaded", function (event) {
  var inner_div = document.getElementById("innerDiv");
  console.log(getComputedStyle(inner_div, null)["backgroundColor"]);
});

#outterDiv {
  background-color: papayawhip;
}

<div id="outterDiv">
  <div id="innerDiv">
    I am an inner div
  </div>
</div>

I want to find out the computed background color of the inner div without having to look into parent(s) element's computed style. Is that possible?

解决方案

You apparently mean to ask

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?

However, your question is confusing because you are using the word "inherited", which has a very specific meaning in CSS, which is not relevant here.

The background-color property is not inherited in the CSS sense. Every element has its own background color, which by default is transparent.

The reason that you inner div looks like it has a papayawhip background is that actually it has a transparent background, which lets the papayawhip background of the outer div show through. There is nothing about the inner div that knows or cares about papayawhip, or that can be queried to return papayawhip.

The only way to find that the inner div is going to have a papayawhip background is to traverse the DOM tree and find the closest parent that has a non-transparent background color. This is explained in the question proposed as a dup target.

By the way, what is your underlying problem here? Why are you trying to do this? There are probably better ways.

这篇关于如何获取从父元素继承的计算背景颜色样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆