如何从一组颜色动态地改变聚合物1.0纸按钮的颜色

How to change polymer 1.0 paper-button color dynamically from an array of colors?

本文关键字:颜色 聚合物 改变 按钮 动态 一组      更新时间:2023-09-26

我有一个数组buttonColors,它有一组十六进制格式的颜色。现在我想显示一组纸按钮,每个按钮的颜色都在buttonColors数组中。如何在聚合物1.0中实现?

<template is="dom-repeat" items="{{buttonColors}}">
      <paper-button style="background-color:{{item}}" >
                  <b>click me</b>
      </paper-button>
</template>

上面的代码片段似乎不起作用。请帮助。

您需要创建一个函数,并以以下方式调用它

<template is="dom-repeat" items="{{buttonColors}}">
      <paper-button style="{{computeStyle(item)}}" >
                  <b>click me</b>
      </paper-button>
</template>
<script>
computedStyle:function(cl)
{
 var s= "background-color:"+cl;
  return s;
}
</script>

ebidel的评论一如既往地出色。(他是负责构建Polymer的Google天才之一)

1.0不支持 {{}} 绑定中的表达式。你需要让它成为一个计算属性: style="{{_computeStyle(item)}}"…文档

下面,我写了一些示例代码供您参考。


示例代码

<dom-module id="x-element">
  <template is="dom-repeat" items="{{buttonColors}}">
    <paper-button style$="{{_computeStyle}}"> <b>click me</b> </paper-button>
  </template> ...
  <script>
    (function() {
      Polymer({
        is: "x-element",
        properties: {
          value: {
            type: Number,
            notify: true
          }
        },
        _computeStyle: function(item) {
          // Compute style here
          return "background-color:red";
        }
      });
    })()
  </script>
</dom-module>