【问题标题】:WebComponents - detect parent overflow and its sizeWebComponents - 检测父溢出及其大小
【发布时间】:2020-07-26 04:45:38
【问题描述】:

我正在开发一个表示简单表格的本机 WebComponent,行数和列数通过属性来。列宽(如果固定)。

如果我有 20 列且列宽 = 150 像素,我只需要在父容器中创建尽可能多的列,而无需创建 y 溢出。

这是我创建表格的方式

...
this._root = this.attachShadow({mode: "open"});
...


_createTable() {
      const parentWidth = this.getRootNode(); // how to get the width of parent container
      console.log(222, parentWidth)

      this._cells = [];
      this._table = document.createElement('table');
      for (let row = 0; row < this._rows; row++) {
        const tr = document.createElement('tr');
        this._table.appendChild(tr);
        this._cells.push([]);
        let totalWidth = 0;
        for (let col = 0; col < this._cols; col++) {
          // can we create a new cell/column
          if (totalWidth + this._columnWidth > parentWidth)
            break;
          totalWidth += this._columnWidth;
          const td = document.createElement('td');
          td.innerText = `cell[${row}${col}]`;
          tr.appendChild(td);
          this._cells[row].push(td);
        }
      }

      this._root.appendChild(this._table);
    }

但我找不到如何从我的web-component 获取父宽度并附加到其调整大小事件的方法。

由于 web-component 在 shadow-dom 中,我无法真正访问父级,也许我在这里错了,但 parentNode 总是返回 null。

想法?

【问题讨论】:

    标签: javascript web-component native-web-component


    【解决方案1】:

    ShadowRoot 是一个 DocumentFragment,因此它们将始终将 parentNode 设置为 null,但它们确实具有指向它们所附加到的元素的 host 属性。

    【讨论】:

    • 来自 shadowDOM 内的任何元素:.getrootNode().host
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2018-11-12
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多