【问题标题】:Modifying custom elements' style in shadow root在阴影根中修改自定义元素的样式
【发布时间】:2018-07-31 17:28:22
【问题描述】:

我正在尝试使用影子 DOM 修改两个自定义 HTML 元素“输出屏幕”和“自定义计算器”的样式。

当我尝试通过附加阴影 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>

【问题讨论】:

  • @Supersharp v1 将是:customElements.define('custom-calculator', class extends HTMLElement { }) ?
  • 是的:看看developers.google.com/web/fundamentals/web-components/… 你也应该在自定义元素构造函数()中创建阴影
  • 我试过这样的事情:customElements.define('custom-calculator', class extends HTMLElement { constructor() { super(); this.innerHTML = [style from before here];}})from the documentation无济于事。我在这里错过了什么?
  • 别忘了创建影子根:this.attachShadow({mode:'open'}).innerHTML=...

标签: javascript html css shadow-dom custom-element


【解决方案1】:

为了对托管 Shadow DOM 的元素(此处为 &lt;custom-calculator&gt;)设置样式,您必须使用 de :host 伪类(而不是在 Shadow DOM 中未知的 custom-calculator)。

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

由于 Shadow DOM 将替换/恢复正常的 DOM 树(此处为 &lt;output-screen&gt;),因此您必须使用 &lt;slot&gt; 在 Shadow DOM 中插入/显示它。

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

然后,为了设置&lt;slot&gt; 元素中显示的内容的样式,您必须使用::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>

【讨论】:

    猜你喜欢
    • 2022-08-19
    • 2015-04-07
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2017-12-30
    • 1970-01-01
    相关资源
    最近更新 更多