在Polymer 2.0中使用JavaScript应用程序更新共享样式

时间:2017-03-31 21:32:11

标签: css polymer polymer-2.x

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

我的问题是我需要更新shared-styles.html中的CSS变量,并让所有其他继承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">

1 个答案:

答案 0 :(得分:3)

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

<强>共享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 CLI的polymer-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中,在菜单中添加<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中,将.circle的{​​{1}}更改为使用background

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

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

  7. GitHub project