![](/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.