【问题标题】:Make css variables bleed to children components使 css 变量流血到子组件
【发布时间】:2023-03-28 19:03:01
【问题描述】:

我正在使用 Polymer 2 构建组件库,但我在 Chrome 以外的浏览器中遇到 css 变量问题。

我有一个包装器组件(x-page),它有一个主题属性,可以是lightdark。我的 CSS 看起来与此类似:

:host([light]) {
    ---color-1: rgb(200,200,200);
    ---color-2: rgb(210,210,210);
}
:host([dark]) {
    ---color-1: rgb(10,10,10);
    ---color-2: rgb(20,20,20);
}

我现在想在这个包装器内的所有组件中使用这些变量(不仅是直接开槽,而且所有组件都包括它们的 shadow-root。

在 Chrome 中这很好用,因为孩子们会从包装器中读取变量,但在其他浏览器中它似乎不起作用,即使我正在使用 apply-shim polyfill 并尝试使用自定义样式.

感谢您的帮助:)

【问题讨论】:

  • 你在使用 Web Components polyfill 吗?
  • 您能否提供更多代码来展示您尝试过的内容。

标签: css web-component polymer-2.x shadow-dom shady-dom


【解决方案1】:

为了使用 Shadow DOM polyfill 应用 CSS 样式,首先您必须准备使用 ShadyCSS.prepareTemplate() 函数附加到影子根的 <template>,如在ShadyCSS polyfill page:

ShadyCSS.prepareTemplate( template1, 'x-page' )

例子:

ShadyCSS.prepareTemplate( template1, 'x-page' )
class XPage extends HTMLElement {
    constructor() {
        super()
        this.attachShadow( { mode: "open" } )
            .appendChild( template1.content.cloneNode( true ) )
    }
}
customElements.define( 'x-page', XPage )
<script src="https://rawgit.com/webcomponents/webcomponentsjs/master/webcomponents-bundle.js"></script>

<template id="template1">
    <style>
        :host([light]) {
            ---color-1: red;
            ---color-2: pink;
        }
        :host([dark]) {
            ---color-1: yellow;
            ---color-2: black;
        }
        span { 
            color: var(---color-1);
            background-color: var(---color-2);
        }
    </style>
    <span><slot></slot></span>
</template>

<x-page light>Light</x-page>
<x-page dark>Dark</x-page>

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 2020-10-17
    • 2014-09-01
    相关资源
    最近更新 更多