【问题标题】:Shadow DOM global css inherit possible?Shadow DOM 全局 css 继承可能吗?
【发布时间】:2018-03-25 22:40:00
【问题描述】:

有没有办法将 :host element css 样式继承到 shadow DOM 中? 原因是如果我们开始开发 Web 组件,每个 Web 组件的样式必须在页面上保持一致。

页面可以有全局css,这个全局css样式可以继承到shadow DOM。有 ::shadow/deep/,但现在已弃用。

或者,这是违反模式的吗?如果有,为什么?

我找到了这个 Q/A,但对我来说似乎已经过时了。 Can Shadow DOM elements inherit CSS?

http://plnkr.co/edit/qNSlM0?p=preview

const el = document.querySelector('my-element');
el.attachShadow({mode: 'open'}).innerHTML = `
  <!-- SEE THIS 'red' is not red -->
  <p class="red">This is defined in Shadow DOM. I want this red with class="red"</p>
  <slot></slot>
`;
  .red {
    padding: 10px;
    background: red;
    font-size: 25px;
    text-transform: uppercase;
    color: white;
  }
<!DOCTYPE html>
<html>

<head>
  <!-- web components polyfills -->
  <script src="//unpkg.com/@webcomponents/custom-elements"></script>
  <script src="//unpkg.com/@webcomponents/webcomponentsjs"></script>
  <script src="//unpkg.com/@webcomponents/shadydom"></script>
  <script src="//unpkg.com/@webcomponents/shadycss@1.0.6/apply-shim.min.js"></script>
</head>

<body>

<div>
  <p class="red">I'm outside the element (big/white)</p>
  <my-element>
    <p class="red">Light DOM content is also affected.</p>
  </my-element>
  <p class="red">I'm outside the element (big/white)</p>
</div>

</body>

</html>

【问题讨论】:

  • 您是否考虑过使用 CSS 变量和 mixins 来代替?如果您公开它们,它们将允许您覆盖或配置组件

标签: html shadow-dom


【解决方案1】:

正如 supersharp 指出的那样,它非常简单,但从您可以在 Internet 上找到的示例中并不明显。以这个基类为例。或者,您可以制作两个不同的(例如 Component 和 ShadowComponent)。还可以选择使用adoptedStyleSheets::part 选择器。

class HtmlComponent extends HTMLElement {
    static ModeShadowRoot = 0;
    static ModeRoot = 1;
    static styleSheets = [];
    static mode = HtmlComponent.ModeShadowRoot;

    #root = null;

    constructor() {
        super();
        if (this.constructor.mode === HtmlComponent.ModeShadowRoot) {
            const shadowRoot = this.attachShadow({ mode: 'closed' });
            shadowRoot.adoptedStyleSheets = this.constructor.styleSheets;
            this.#root = shadowRoot;
        } else {
            this.#root = this;
        }
    }

    get root() {
        return this.#root;
    }

    init() {
        this.root.innerHTML = this.render();
    }

    render() {
        return '';
    }
}


class Test extends HtmlComponent {
    static mode = HtmlComponent.ModeRoot;

    constructor() {
        super();
        super.init();
    }

    render() {
        return `
            <div>
                <x-nested-component></x-nested-component>
            </div>
        `;
    }
}

【讨论】:

    【解决方案2】:

    Shadow DOM 的一个特点是隔离 CSS 样式。

    因此,如果您希望自定义元素从主页继承样式,请不要使用 Shadow DOM。这不是强制性的。

    【讨论】:

      猜你喜欢
      • 2014-10-02
      • 2018-04-21
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 2019-06-26
      相关资源
      最近更新 更多