HTML exportparts属性测试实例页面

回到相关文章 »

效果:

代码:

CSS代码:
c-e::part(textspan) { color: red; }
c-e-outer::part(textspan) { color: red; }
c-e-inner::part(textspan) { color: red; }
HTML代码:
<template id="c-e-outer-template">
  <c-e-inner exportparts="innerspan textspan"></c-e-inner>
</template>

<template id="c-e-inner-template">
  <p part="innerspan">
    这段文字会是红色,因为这段文字host中的innerspan转换成了"textspan",和样式匹配了。
  </p>
  <p part="textspan">
      这段文字不会是红色,因为在内部的自定义元素中textspan是没法匹配的。
  </p>
</template>

<c-e></c-e>
<c-e-inner exportparts="innerspan textspan"></c-e-inner>
<c-e-outer></c-e-outer>
                
JS代码:
let innerTemplate = document.getElementById('c-e-inner-template');
let outerTemplate = document.getElementById('c-e-outer-template');

globalThis.customElements.define('c-e-inner', class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(document.importNode(innerTemplate.content, true));
  }
});
globalThis.customElements.define('c-e-outer', class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    
    this.shadowRoot.appendChild(document.importNode(outerTemplate.content, true));
  }
});
globalThis.customElements.define('c-e', class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(document.createElement('c-e-outer'));
  }
});