簡體   English   中英

在Polymer中,單擊時可以動態創建紙按鈕更改顏色嗎?

[英]In Polymer can I make a dynamically created paper-button change color when I click it?

我正在嘗試更改通過<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>

現在,例如,當我單擊按鈕“高”時,我想要更改該按鈕的背景顏色,並且也希望更改“低”按鈕的背景顏色。 Array項存儲在本地,並且我可以使用以下代碼執行類似的操作:

<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都將是活動類的一部分(我用來設置背景顏色的樣式),而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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM