Javascript 如何更改单击时评级字段的颜色?
当用户单击星号(Javascript 如何更改单击时评级字段的颜色?,javascript,angular,Javascript,Angular,当用户单击星号(*)时,我们是否可以更改评级字段(*)的颜色。例如,当用户单击第三个开始(*)时,第一个三星应该是红色 我可以获得所选的索引,但如何将颜色更改为单击角中的星形 这是我的密码 HTML 评级 * 您可以使用[style.color] <h1>Rating</h1> <div [style.color]="index==0?'gray':index==1?'red':index==2?'blue':index==3?'yellow':'black'
*
)时,我们是否可以更改评级字段(*
)的颜色。例如,当用户单击第三个开始(*
)时,第一个三星应该是红色
我可以获得所选的索引
,但如何将颜色更改为单击角中的星形
这是我的密码
HTML
评级
- *
您可以使用[style.color]
<h1>Rating</h1>
<div [style.color]="index==0?'gray':index==1?'red':index==2?'blue':index==3?'yellow':'black'">
<ul >
<li *ngFor="let i of arr;let in =index" [style.color]="in>index?'gray':'inherit'"
(click)="onClickItem(in)">*</li>
</ul>
</div>
并删除.css中的行
li
{
color:gray //<--remove this line
...
}
li
{
颜色:灰色//我将定义一个与所选星形相关的类,并使用[ngClass]
app.component.ts
export class AppComponent {
title = "CodeSandbox";
arr: any[] = [];
selectedRate:number = -1;
constructor() {
this.arr = [1, 2, 3, 4, 5];
}
onClickItem(index) {
this.selectedRate=index
}
}
app.component.css
li.selected {
color: red;
}
app.template.html
<ul>
<li *ngFor="let i of arr;let in =index" (click)="onClickItem(in)"
[ngClass]="{selected:in <= selectedRate}">*</li>
</ul>
- *
愉快的编码。基本上,如果您可以处理onClick
并且可以对单击的元素进行索引,您可以将单击的索引元素存储在控制器中,并使用[ngClass]
指令在模板上使用条件呈现:
<ul>
<li *ngFor="let i of arr;let in =index" (click)="onClickItem(in)" [ngClass]="getStarClass(in)">*</li>
</ul>
我不想使用[style.color]
指令绑定只是为了不将样式与文档结构混用。当然,你需要定义这两个css类来处理样式设置我只能建议你使用一个已经编码好的评级插件。有很多东西也应该与angular一起使用,你想要实现的一切都已经构建好了;)
li.selected {
color: red;
}
<ul>
<li *ngFor="let i of arr;let in =index" (click)="onClickItem(in)"
[ngClass]="{selected:in <= selectedRate}">*</li>
</ul>
<ul>
<li *ngFor="let i of arr;let in =index" (click)="onClickItem(in)" [ngClass]="getStarClass(in)">*</li>
</ul>
onClickItem(in) {
this.clickedIdx = in
}
getStarClass(in: number) {
if (in >= this.clickedIdx) return { 'color-gray': true, 'color-red': false }
else return { 'color-gray': false, 'color-red': true}
}