问题
I noticed that when I do the following (note: this is Shadow DOM v1!)
let div = document.querySelector('div');
let root = div.attachShadow({mode: 'closed'});
let span = document.createElement('span');
span.textContent = 'Super hot!';
root.appendChild(span);
*{
background: rgba(0,0,0,.1);
color: rgba(0,0,0,.4);
}
<div></div>
The color
property is propagated in to the shadow root, whilst the background
property is not. Which part of the specification defines this behavior and why is this? I was under the impression that shadow roots were primarily meant for the encapsulation of DOM trees.
Screenshot of the above snippet:
Screenshot of the above snippet without the background
and with just color: green
回答1:
It's an optical illusion, due to the use of *
and opacity.
The span
didn't inherit from the span CSS rule, the color and background are propagated from the div
element under the shadow.
See code below with distinct colors. Inspect the Styles properties with Chrome Dev Tool to see the ones that apply.
let div = document.querySelector('div')
let root = div.attachShadow({mode: 'closed'})
let span = document.createElement('span')
span.textContent = "Text in the SPAN, but colors from DIV"
root.appendChild(span)
div {
/*background-color: rgba(0,255,0,.1);*/
color: green;
}
span {
background-color: rgba(255,0,0,.2);
color: red;
}
<h4>SPAN in Shadow DOM:</h4>
<div id="v1">Text and colors from DIV</div>
<h4>No Shadow DOM:</h4>
<div>Text and colors from DIV<span>Text and colors from SPAN</span></div>
Update: As @poke stated:
The shadow DOM only shuts off the CSS rules but not the inheritance that happens in the document.
That's why the name "Shadow" is expressive and meaningfull.
What you experienced with the background is also true for normal CSS and DOMs (not related to Shadow DOM encapsulation).
来源:https://stackoverflow.com/questions/38740945/why-does-color-affect-shadow-roots