HTML 自定义元素没有宽度

HTML custom element has no width

我创建了自定义元素并设置了它的尺寸和背景颜色。但在页面中它不呈现任何东西。在 DOM 中它存在,但不可见。

export class BaseLayout extends HTMLElement{
    constructor() {
        super();
        this.style.backgroundColor="red";
        this.style.width = "500px";
        this.style.height = "500px";
    }
}
customElements.define("base-layout", BaseLayout);

当我添加内容(通过 innerText)时,出现红色背景,但仅作为该文本的背景(而不是 500 像素的宽度和高度)。

我解决它的一种方法是扩展 HTMLDivElement 而不是 HTMLElement。但是当我这样做时,我失去了我喜欢的自定义 html 标签(它将被 DIV 取代)。有什么办法可以避免吗?

谢谢!

您只需将其 display 属性 设置为 'block''inline-block'.

this.style.display = 'block';

因此,您的示例将如下所示:

export class BaseLayout extends HTMLElement{
    constructor() {
        super();
        this.style.backgroundColor="red";
        this.style.width = "500px";
        this.style.height = "500px";
        this.style.display = "block";
    }
}
customElements.define("base-layout", BaseLayout);