【问题标题】:HTML custom element has no widthHTML 自定义元素没有宽度
【发布时间】:2021-03-11 00:03:45
【问题描述】:

我创建了自定义元素并设置了它的尺寸和背景颜色。但在页面中它不呈现任何东西。在 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 取代)。有办法避免吗?

谢谢!

【问题讨论】:

    标签: javascript html css typescript custom-element


    【解决方案1】:

    您只需将其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);
    

    【讨论】:

      猜你喜欢
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 2019-03-10
      • 1970-01-01
      • 2020-08-10
      • 2017-11-10
      • 2017-06-02
      相关资源
      最近更新 更多