修改影子根中自定义元素的样式

Modifying custom elements' style in shadow root

我正在尝试使用阴影 DOM 修改两个自定义 HTML 元素 "output-screen" 和 "custom-calculator" 的样式。

当我尝试通过附加阴影 DOM 来执行此操作时,如下所示,样式未应用。知道我做错了什么吗?

JS Fiddle

<custom-calculator id="calculator">
  <output-screen></output-screen>
</custom-calculator>

<script>
var o = Object.create(HTMLElement.prototype);
    var oElement = document.registerElement('output-screen', {
        prototype: o
    });

var c = Object.create(HTMLElement.prototype);
var cElement = document.registerElement('custom-calculator', {
  prototype: c
});

var calc = document.querySelector('#calculator')
calc.attachShadow({ mode: 'open' });
calc.shadowRoot;
calc.shadowRoot.innerHTML = `
<style>
output-screen{
display:inline-block;
background-color:orange;
width:50%;
height:100vh;
}
custom-calculator {
display:inline-block;
background-color:grey;
width:100%;
height:100vh;
vertical-align:top;
}
</style>
`;
</script>

为了给承载阴影 DOM 的元素设置样式,这里 <custom-calculator>,您必须使用 de :host 伪 class(而不是 custom-calculator 在 Shadow 中未知 DOM).

:host {
  display:inline-block;
  background-color:grey;
  width:100%;
  height:100vh;
  vertical-align:top;
}

因为阴影 DOM 将 replace/recover 普通的 DOM 树(这里 <output-screen>),你必须使用 <slot> 到 insert/reveal 它在阴影中 DOM.

calc.shadowRoot.innerHTML = `
  <style>
    ...
  </style>
  <slot></slot>`

然后,为了设置 by/in <slot> 元素显示的样式,您必须使用 ::slotted() 伪元素:

::slotted( output-screen ){
  display:inline-block;
  background-color:orange;
  width:50%;
  height:100vh;
}

实例:

var calc = document.querySelector('#calculator')
calc.attachShadow({mode: 'open'});
calc.shadowRoot.innerHTML = `
  <style>
    :host {
      display:inline-block;
      background-color:grey;
      width:100%;
      height:100vh;
      vertical-align:top;
    }

    ::slotted( output-screen ){
      display:inline-block;
      background-color:orange;
      width:50%;
      height:100vh;
    }
  </style>
  <slot></slot>`;
<custom-calculator id="calculator">
  <output-screen></output-screen>
</custom-calculator>