![](/img/trans.png)
[英]How do I change the color of a button so that it changes to another color when its clicked using jQuery?
[英]How can I change the color of my button based on its value when using ngIf in Ionic/Angular
我有一個 html 頁面,它使用 ngIf 根據我之前在方法調用 getButton() 中提供的數字生成x個按鈕,該方法是開始按鈕上的單擊偵聽器。
<ion-content>
<ion-button (click)="getButton(15)">
Start
</ion-button>
<ion-button *ngFor ="let element of buttonArray" (click)="checkAnswer(element.value)">
{{ element.value }}
</ion-button>
</ion-content>
按鈕的值從顏色數組中隨機化,然后推入長度等於所需按鈕數量的按鈕值數組中。
colorsArray : string[] = ['Red', 'Blue', 'Green', 'Yellow']
getButton(i: number){
let c: number ;
for (c=0; c<i; c++) {
this.buttonArray.push((this.colorsArray[(Math.floor(Math.random()*4))])
}
}
輸出是帶有來自colorsArray 的隨機值的x個按鈕。
如何將按鈕的顏色更改為按鈕的值(代碼中的 element.value),即值為 'red' 的按鈕必須為 'red',值為 'blue' 的按鈕必須為必須是藍色。
您可以通過此功能生成隨機顏色:
getRandomColor(){
let color = "#";
for (let i = 0; i < 3; i++)
{
let part = Math.round(Math.random() * 255).toString(16);
color += (part.length > 1) ? part : "0" + part;
}
return color;
}
並用顏色初始化你的數組:
this.buttonArray.forEach((e)=>{
e.color = this.getRandomColor();
})
和在 html: 使用ngStyle
顯示生成的顏色。
<ion-button *ngFor ="let element of buttonArray" (click)="checkAnswer(element.value)" [ngStyle]="{background-color: element.color}">
{{ element.value }}
</ion-button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.