在Polymer 2.0中,使用JavaScript应用程序范围内更新共享样式。

4

我有一个 shared-styles 元素,它定义了我的应用程序的大部分颜色。如果我使用CSS变量,我可以轻松地在 shared-styles.html 中手动更改颜色,并让所有其他组件都从中继承。

我的问题是,我需要更新 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个回答

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>

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

示例

这里是使用Polymer CLI的polymer-2-starter-kit模板的说明:

  1. Install the bleeding edge Polymer CLI (npm install polymer-cli@next), required for the polymer-2-starter-kit template.

  2. Run:

    mkdir polymer-2-shared-styles-demo
    cd polymer-2-shared-styles-demo
    polymer init polymer-2-starter-kit
    
  3. In src/my-app.html, add a <button> to the menu, which will change the value of --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. In src/shared-styles.html, change .circle's background to use --app-primary-color:

    .circle {
    
      /* ***    LINE 33: Use --app-primary-color below     **** */
      background: var(--app-primary-color, #ddd);
    
  5. Run polymer serve -o to open the starter kit in the default browser.

  6. Click the button in the menu to change the color of the toolbar and the circles in each page. It should look like this: screenshot

GitHub项目

GitHub项目


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接