如果没有`<slot />`而是影子根,子节点会发生什么

考虑以下代码:

//js
class FooBar extends HTMLElement {
  constructor(){
    super();
  }
}

customElements.define('foo-bar', FooBar);


<!-- html -->
<foo-bar>
  <h1>Test</h1>
</foo-bar>

这将在浏览器中显示»Test«。

如果构造函数更改为:

constructor () {
  super();
  this.shadow = this.attachShadow({ mode: 'open' }) 
}

“测试”消失了,因为现在有一个影子根。

如果构造函数进一步更改为

constructor () {
  super();
  this.shadow = this.attachShadow({ mode: 'open' });
  this.shadow.appendChild(document.createElement('slot')); 
}

The »Test« appears again, since there is now a default slot for all child Nodes of <foo-bar>

But what happens to the child nodes if there is no <slot /> within the shadow root. They still appear within this.children and its style.display property remains "". So they are within the dom, but rendered? What exactly happens here?

评论