javascript - 在 Polymer 中,我可以使动态创建的纸按钮在单击时改变颜色吗?

标签 javascript html css polymer dom-repeat

我正在尝试更改通过 <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;
}

关于javascript - 在 Polymer 中,我可以使动态创建的纸按钮在单击时改变颜色吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56689948/

相关文章:

javascript - 如果未登录,则重定向 html 页面

javascript - 样式属性不适用于带后缀或前缀的输入

html - CSS - 当链接的 img 显示 : block 时事件链接断开

css - 如何使用带有伪元素的选择器属性?

html - 为什么我的第一个子选择器不能处理具有指定类的选择中的第一个元素?

javascript - 如何正确发布 AMD 模块以便 RequireJS 可以定位依赖项?

javascript - 带数组的 vue.js v 模型

html - 使用 z-index 定位三个 div

javascript - 使用按钮使用javascript更改整个网站的字体大小

javascript - 通过javascript发送网页