【发布时间】: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