【问题标题】:<table> child elements usage in shadow dom<table> 子元素在 shadow dom 中的使用
【发布时间】:2021-03-25 09:47:39
【问题描述】:

是否有任何约束阻止 &lt;thead&gt;&lt;tbody&gt;&lt;tr&gt; 等插入影子 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 中,并且无法覆盖来自在自定义元素之外。

【问题讨论】:

  • &lt;tr&gt; 需要 &lt;table&gt; 父级。所以在这个用例中更好地解析 lightDOM 并将它们注入到表中
  • 这与影子 DOM 无关。 &lt;thead&gt;&lt;tbody&gt;&lt;tfoot&gt; 只允许 &lt;tr&gt;s 作为子元素。
  • 不幸的是,@Andreas 是对的,w3.org/TR/html52/tabular-data.html#the-table-element - 表不允许 &lt;slot&gt; 作为其子级或其任何后代的子级。

标签: javascript html web-component shadow-dom


【解决方案1】:

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

【讨论】:

  • 是的,今天也提出了问题:github.com/whatwg/html/issues/6226,但请参阅 Anne 他的回答,他们不会弄乱解析器。正如我在上面的 cmets 中所说,您可以自己将那些 TR 从 lightDOM 移动到 shadowDOM:this.shadowRoot.querySelector("TBODY").append(...[this.querySelectorAll("TR")])
  • 我正在构建一个使用这些元素的库,我无法将这些东西注入到我的影子 DOM 中,我也不愿意用 JS 来做,谢谢你的建议。
【解决方案2】:

将其他标签放在table上是不正确的然后你应该使用css propdisplay: table-cell;display: table-rowdisplay: 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>

【讨论】:

    猜你喜欢
    • 2020-03-16
    • 2021-08-28
    • 2020-07-31
    • 1970-01-01
    • 2019-02-27
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    相关资源
    最近更新 更多