如何使用点击功能更改聚合物中的图标

时间:2015-06-27 00:04:18

标签: polymer

我有铁添加,我用于一个手风琴风格的页面。在切换手风琴时,我想制作图标

图标="添加"是+符号和图标="删除"是一个减号。该图标表示是否展开。

<accordion-question>
     <iron-icon icon="add"></iron-icon>
           This is the question
</accordion-question> 

<accordion-answer>
  This is the answer which appears if you toggle
</accordion-answer>

3 个答案:

答案 0 :(得分:2)

我认为使用Polymer(dom).setAttribute(attr, value)在js中设置属性更容易,而不是乱用计算绑定。

<dom-module is="test-element">
    <template>
        <iron-icon icon="add" on-click="_onClick"></iron-icon>
        <iron-collapse>
            <p>Collapse Content</p>
        </iron-collapse>
    </template>
</dom-module>
<script>
Polymer({
    is: "test-element",
    _onClick: function() {
        var button= this.querySelector('iron-icon'),
            collapse = this.querySelector('iron-collapse')
        collapse.toggle()
        if (collapse.opened) {
            Polymer.dom(button).setAttribute('icon', 'remove')
        } else if (!collapse.opened) {
            Polymer.dom(button).setAttribute('icon', 'add')
        }
    }
})
</script>

CSS解决方案也非常吸引人,但因为它简化了js逻辑。

答案 1 :(得分:1)

这样的东西
<iron-icon icon="{{_getIcon(expanded)}}"></iron-icon>

然后

onToggle: function () {
  //Maybe this is your click event
  this.expanded = !this.expanded
},
_getIcon: function () {
  if (this.expanded) {
    return 'add';
  }
  return 'remove';
}

修改:根据@ScottMiles的建议改进_getIcon功能

_getIcon: function(expanded) {
  return expanded ? 'add' : 'remove; 
}

答案 2 :(得分:0)

我假设accordion-question会有某种开/关类或属性,这应该像以下一样简单:

<style>
  accordion-question:not(.open) iron-icon[icon="add"],
  accordion-question.open iron-icon[icon="remove"] {
    display: inline-flex;
  }

  accordion-question:not(.open) iron-icon[icon="remove"],
  accordion-question.open iron-icon[icon="add"] {
    display: none;
  }
</style>

<!-- Shows "add" icon -->
<accordion-question>
  <iron-icon icon="add"></iron-icon>
  <iron-icon icon="remove"></iron-icon>
  This is the question.
</accordion-question>

<!-- Shows "remove" icon -->
<accordion-question class="open">
  <iron-icon icon="add"></iron-icon>
  <iron-icon icon="remove"></iron-icon>
  This is the question.
</accordion-question>