首页 > 解决方案 > 使用 lit-html 用 Shadow DOM 封装自定义元素的 CSS

问题描述

试图使一些css仅适用于使用 Shadow DOM 的自定义元素。对于渲染,我使用lit-html.

有任何想法吗?或者其他一些方法来完成没有阴影的封装?

<!DOCTYPE html>
<html>
<head>
  <meta charset='UTF-8'>
  <script type='module' src="script.js"></script>
  <title>LitComponent</title>
</head>
<body>
<lit-component></lit-component>
<p>not styled</p>
</body>
</html>

js

import { html, render } from "./node_modules/lit-html/lit-html.js";

class LitComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'open'})
  }

  connectedCallback() {
    let style = document.createElement('style');
    style.innerHTML = `
    p {
      font-size: 80px;
    }
    `
    this.shadowRoot.appendChild(style);
    render(this.createView(), this);
  }

  createView() {
    return html`
      <p> styled </p>
    `;
  }
}
customElements.define("lit-component", LitComponent);

强文本

我希望在我LitComponent的样式中包含“样式”段落,font-size: 80px;而不是普通标记段落。

但实际上,当像这样附加阴影时,它根本没有渲染我的组件。

在此处输入图像描述

标签: javascriptcssshadow-domcustom-elementlit-html

解决方案


解决了

render(this.createView(), this.shadowRoot);

推荐阅读