4

我有一个shared-styles元素可以保留我的大部分应用程序颜色。我可以轻松地手动更改颜色shared-styles.html,如果我使用 CSS 变量,我的所有其他组件都可以从那里继承。

我的问题是我需要更新 CSS 变量,shared-styles.html并让所有其他继承 CSS 变量的组件相应地更新它们的颜色。下面是我的shared-styles.html。为简洁起见,我删除了除--app-primary-color.

<link rel="import" href="../bower_components/polymer/polymer-element.html">

<!-- shared styles for all views -->
<dom-module id="shared-styles">
  <template>
    <style is="custom-style">
      :host {
        --app-primary-color:#2196F3;
      }
    </style>
  </template>
  <script>
    class SharedStyles extends Polymer.Element {

      static get is() { return 'shared-styles'; }

      ready(){
        super.ready();
        console.log('update css');
        this.updateStyles({'--app-primary-color': 'red'});
      }
    }
    window.customElements.define(SharedStyles.is, SharedStyles);
  </script>
</dom-module>

这就是我将它们包含在其他组件中的方式。例如:

<dom-module id="test-element">
  <template>
    <style include="shared-styles">
4

1 回答 1

5

共享样式不是 Polymer 元素,因此它不应该扩展Polymer.Element,也不应该有<script>标签。它应该这样定义:

shared-styles.html

<link rel="import" href="../bower_components/polymer/polymer-element.html">

<!-- shared styles for all views -->
<dom-module id="shared-styles">
  <template>
    <style>
      :host {
        --app-primary-color: #2196F3;
      }
    </style>
  </template>
</dom-module>

然后,调用this.updateStyles根元素(例如<my-app>)以在 Polymer 2.0 中应用全局样式。请注意,下面的所有元素<my-app>都将继承新指定的样式。

例子

以下是使用 Polymer CLIpolymer-2-starter-kit模板的说明:

  1. 安装模板npm install polymer-cli@next所需的前沿 Polymer CLI ( )。polymer-2-starter-kit

  2. 跑:

    mkdir polymer-2-shared-styles-demo
    cd polymer-2-shared-styles-demo
    polymer init polymer-2-starter-kit
    
  3. src/my-app.html中,将 a 添加<button>到菜单中,这将更改 的值--app-primary-color

    <template>
      <app-drawer-layout fullbleed>
        <!-- Drawer content -->
        <app-drawer id="drawer" slot="drawer">
          <app-toolbar>Menu</app-toolbar>
    
          <!-- ****     LINE 77: Add button below      **** -->
          <button on-click="_changeAppColor">Change app color</button>
    
    <script>
      class MyApp extends Polymer.Element {
    
        /* ***    LINE 130: Define button-click handler below     **** */
        _changeAppColor() {
          this.updateStyles({'--app-primary-color': 'red'});
        }
    
  4. 在中src/shared-styles.html,更改为使用:.circlebackground--app-primary-color

    .circle {
    
      /* ***    LINE 33: Use --app-primary-color below     **** */
      background: var(--app-primary-color, #ddd);
    
  5. 运行polymer serve -o以在默认浏览器中打开入门工具包。

  6. 单击菜单中的按钮可更改工具栏的颜色和每页中的圆圈。它应该如下所示: 截屏

GitHub项目

于 2017-03-31T22:41:03.253 回答