动态更改星级中每个元素的颜色

时间:2019-01-02 09:01:57

标签: html css angular

我已经实施星级评定,并且效果很好。现在要求每个星星都有不同的颜色,我的星星颜色来自CSS,其颜色为GOLD。如何给它提供不同的颜色。例如-第一颗星星应该是红色,第二颗蓝色,第三颗绿色等等。

<fieldset class="rating">
    <ng-container *ngFor="let star of starList">
        <input type="radio" id="th {{star.id}} {{j}}" name="th_{{j}}" (click)="updateRating(star.value,kpi.kpiId)" />
        <label [class]="star.class" for="th {{star.id}} {{j}}" [title]="star.value"></label>
    </ng-container>
</fieldset>

Css:

.rating {
    border: none;
    float: left;
    direction: ltr;
}

.rating>input {
    display: none;
}

.rating>label:before {
    margin: 5px;
    font-size: 1.25em;
    font-family: "Font Awesome 5 Free";
    display: inline-block;
    content: "\f005";
    font-weight: 900;
}

.rating>.half:before {
    content: "\f089";
    position: absolute;
}

.rating>label {
    color: #ddd;
    float: right;
}

.rating>input:checked~label,

/* show gold star when clicked */  

.rating:not(:checked)>label:hover,

/* hover current star */ 

.rating:not(:checked)>label:hover~label {
    color: gold;
    cursor: pointer;
}

2 个答案:

答案 0 :(得分:1)

这是一个示例,您可以如何简单地为1颗星到5颗星的每个阶段创建一个类

.rate-1 label:nth-child(1){
  background: red;  
}

.rate-2 label:nth-child(1) ,.rate-2 label:nth-child(2){
  background: orange;  
}

.rate-3 label:nth-child(1) ,.rate-3 label:nth-child(2) , .rate-3 label:nth-child(3){
  background: blue;  
}

.rate-4 label:nth-child(1) , .rate-4 label:nth-child(2) , .rate-4 label:nth-child(3) ,.rate-4 label:nth-child(4){
  background: yellow;  
}


.rate-5 label:nth-child(1) , .rate-5 label:nth-child(2) , .rate-5 label:nth-child(3) , .rate-5 label:nth-child(4) , .rate-5 label:nth-child(5){
  background: green;  
}

模板

<fieldset class="rating" [attr.class]="'rate-'+selectedValue">
    <ng-container *ngFor="let star of starList" >
        <label>
           <input type="radio" [value]="star" (click)="updateValue(star)"/> ★
        </label>
    </ng-container>
</fieldset>


{{selectedValue}}

stackblitz demo

答案 1 :(得分:0)

检查以下代码可能会对您有所帮助:

.yellow{
  color:yellow
}
.purple{
  color:purple
}
.blue{
  color:blue
}
.green{
  color:green
}
<div [ngClass] = "noOfStars==1 ?'yellow':noOfStars==2?'purple':noOfStars==3?'blue':noOfStars==4?'green'"></div>