<table> 阴影中的子元素使用 dom

<table> child elements usage in shadow dom

是否有任何限制阻止 <thead><tbody><tr> 等在影子 DOM 中插入?

给定以下示例:

<script>
class Table extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({mode: 'open'}).innerHTML = `
            <table>
                <thead>
                    <slot name="header"></slot>
                </thead>
                <tbody>
                    <slot name="row"></slot>
                </tbody>
            </table>
        `;
    }
}
window.customElements.define('data-table', Table);
</script>
<data-table>
    <tr slot="header">
        <th>header1</th>
    </tr>
    <tr slot="row">
        <td>cell1</tr>
    </tr>
</data-table>

呈现为以下结构:

解决方法是使用模板并在 slotchange 事件处理程序中使用 JS 插入模板内容,但我想避免这种情况,因为克隆的内容最终会出现在影子 DOM 中并且它将无法从自定义元素外部覆盖样式。

如评论中所述,根据自定义元素规范 v1,目前这是不可能的。
规范将 <table> 的标签限制为一组 <tbody><thead> 等等加上 <script><template>.
浏览器供应商不愿意将更改合并到他们的 HTML 解析器 https://github.com/WICG/webcomponents/issues/59.
猜猜目前唯一的解决方案是使用具有一堆 aria-* 属性的 divs 网格。

将其他标签放在 table 上是不正确的 那么你应该使用 css prop ( display: table-cell;, display: table-row, display: table-header-group;display: table-footer-group;) 与其他标签。

但如果您仍想使用 table,

您可以使用如下功能附加标签:

lit playground

import {html, css, LitElement} from 'lit';
import {customElement, property} from 'lit/decorators.js';

@customElement('data-table')
export class dataTable extends LitElement {
  static styles = css`
      table {
       border:1px solid;
      }
  `;
  render() {
    return html`
     <table>
        ${this.templateGen()}
     </table>
    `;
  }
  
  
  templateGen() {
   return html`<slot></slot>`;
  }
}
<!DOCTYPE html>
<head>
  <script type="module" src="./simple-greeting.js"></script>
</head>
<body>
  <data-table><p>Test slot in table<p></data-table>
</body>