从元素atrribute覆盖样式

时间:2016-02-01 19:40:42

标签: polymer

我正在尝试通过改变它的属性来创建一种可以成为风格的聚合物组件。

我的基本组件如下:

  <dom-module id="item">
  <template>
      <style>

          #item {
              display: border-box;
              line-height: 1rem;
              color: var(--boxcolor, #345d83);
              margin: 10px;
              border-radius: 4px;
              border-top: 1px solid transparent;
              border-right: 1px solid transparent;
              border-bottom: 1px solid transparent;
              border-left: 4px solid #f2f2f2;
          }

          #item:hover {
              background-color: #f5f9fd;
              border-left: 4px solid var(--boxcolor, #345d83);
              border-top: 1px solid #f2f2f2;
              border-right: 1px solid #f2f2f2;
              border-bottom: 1px solid #f2f2f2;
          }

          .box {
              padding: 10px;
          }

          .subtitle {
              font-size: .9rem;
          }

      </style>

      <div id="item">
          <div class="box">
              <content></content>
              <div class="subtitle">
                  <strong>{{value}}</strong> {{label}}
              </div>
          </div>
      </div>
  </template>

  <script>
      Polymer({
          is: 'item',
          properties: {
              value: String,
              label: String,
              boxcolor: String
          }
      });
  </script>

我要做的是使用这个元素:

<item value="5x" label="cooler than Hello!" boxcolor="#f00">My World now!</item>

1 个答案:

答案 0 :(得分:3)

有不同的方法来完成这项工作。我的建议是使用下面链接中描述的自定义属性api。

https://www.polymer-project.org/1.0/docs/devguide/styling.html#style-api

基本上,只要属性--boxcolor发生变化,您就需要更新自定义样式变量boxcolor。以下是更新的脚本。

<script>
  Polymer({
      is: 'item',
      properties: {
          value: String,
          label: String,
          boxcolor: {
            type: String,
            observer: '_boxColorChange'
          }
      },
      _boxColorChange: function(newValue) {
        this.customStyle['--boxcolor'] = newValue;
        this.updateStyles();
      }
  });
</script>

更新:看起来原始代码中定义了自定义样式变量。我错过了那一部分。我已更新代码以更新原始代码中可用的自定义样式变量。

相关问题