javascript - 在 Polymer 中,我可以在单击时动态创建纸质按钮更改颜色吗?
问题描述
我正在尝试更改通过<template is="dom-repeat">
元素动态创建的纸质按钮的颜色。假设我有这段代码:
<template is="dom-repeat" items="{{items}}" as="item">
Itemnumber: [[item.number]] is [[item.height]].
<paper-button on-click="setHigh">High</paper-button>
<paper-button on-click="setLow">Low</paper-button>
</template>
现在,例如,当我单击“高”按钮时,我希望该按钮的背景颜色发生变化,并且我希望“低”按钮的背景颜色也发生变化。数组项存储在本地,我已经能够使用以下代码执行类似的操作:
<template is="dom-repeat" items="{{items}}" as="item">
Itemnumber [[item.number]] is [[item.height]].
<template is="dom-if" if="[[isHigh(item)]]">
<paper-button on-click="setHigh" class="active">High</paper-button>
<paper-button on-click="setLow">Low</paper-button>
</template>
<template is="dom-if" if="[[!isHigh(item)]]">
<paper-button on-click="setHigh">High</paper-button>
<paper-button on-click="setLow" class="active">Low</paper-button>
</template>
</template>
现在,每个返回 isHigh(item) 为 true 的 Item 都将成为 active 类的一部分(我用它来设置背景颜色的样式),而 false 将不是该类的一部分。这在我第一次加载页面时有效,但是当我按下按钮并且 Items 数组发生更改时,我必须首先重新加载页面才能使样式生效。属性 item.height 会立即更新。
解决方案
我建议在两个按钮周围添加一个容器,在该容器上添加一个为按钮着色的类。使用 css 执行此操作对您的应用程序来说要轻得多,因为它不需要在按下按钮时调用 getHigh。
<template is="dom-repeat" items="{{items}}" as="item">
<div class="button-container">
Itemnumber [[item.number]] is [[item.height]].
<paper-button on-click="setHigh" class="high">High</paper-button>
<paper-button on-click="setLow" class="low">Low</paper-button>
</div>
</template>
然后让函数在它们周围的 div 上添加和删除一个类
setHigh(e) {
e.currentTarget.classList.add("high")
}
setLow(e) {
e.currentTarget.classList.remove("high")
}
在你的 CSS 中:
.button-container .high {
background-color: green;
}
.button-container .low {
background-color: red;
}
/* When high is pressed */
.button-container.high .high {
background-color: red;
}
.button-container.high .low {
background-color: green;
}
推荐阅读
- python - 无论顺序如何,都在 python 中返回一对唯一的列
- amazon-web-services - CloudFront 缓存包含授权数据的页面并将其提供给未经授权的用户是否存在任何危险?
- installation - 如何对包中的签名二进制文件进行身份验证?
- sql - 如何减去“Sysdate”的日期范围
- python - 需要制作一个数据框来记录每个文件夹中文件类型的数量
- excel - Excel VBA - [Microsoft][ODBC 文本驱动程序] 记录太大
- algorithm - 对 DP 表中的一行进行排序以提取解决方案是否常见?
- java - 有条件地添加 Spring 应用程序兄弟
- python - 有没有解决递归问题的好方法?
- woocommerce - 有什么方法可以隐藏 WP 管理员角色的 Woocommerce 选项卡吗?