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

时间:2018-07-31 17:28:23

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

我试图使用阴影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>

1 个答案:

答案 0 :(得分:3)

为了设置托管Shadow DOM的元素的样式,在这里<custom-calculator>,必须使用de :host伪类(而不是Shadow DOM内部未知的custom-calculator

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

由于Shadow DOM将替换/恢复普通DOM树(此处为<output-screen>),因此您必须使用<slot>将其插入/显示在Shadow DOM中。

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

然后,为了设置<slot>元素/在::slotted( output-screen ){ display:inline-block; background-color:orange; width:50%; height:100vh; } 元素中所显示的内容的样式,您必须使用::slotted()伪元素:

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>
        final DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
        try {
            final java.util.Date startDate = dateFormat.parse(session.getStartTime__c());
            startTime = new Time(startDate.getTime());
        } catch (ParseException e) {
            LOG.error(e.getMessage(), e);
        }   // try