如何在五星评级中更改每颗星的颜色?

时间:2017-11-10 16:58:08

标签: html css

所以我现在得到了以下代码:

HTML:

<div class="star-rating">
        <span class="fa fa-star-o" data-rating="1" data-color="red"></span>
        <span class="fa fa-star-o" data-rating="2"></span>
        <span class="fa fa-star-o" data-rating="3"></span>
        <span class="fa fa-star-o" data-rating="4"></span>
        <span class="fa fa-star-o" data-rating="5"></span>
        <input type="hidden" name="whatever1" class="rating-value" value="4.0">
      </div>

CSS:

.star-rating {
  line-height:32px;
  font-size:5em;
}

.star-rating .fa-star{
    color: #28a745;
}

目前,无论您选择哪种星标,它都是绿色之星。我想这样做,如果你只点击1或2颗星,它们就是红色。如果它是三个,那么它们是橙色的,如果它是四个或五个,它们是绿色的。 有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

尝试一下我给了你一个提示。在此基础上你可以继续进行

$(document).ready(function(){

  $(".star").click(function(){
  $var =$(this).attr("data-rating");
    $("span").css("color","#000");    
  if($var <3)
  {
    $("span").slice(0,$var).css("color","red");    
  }
  else   if($var <= 4)
  {
    $("span").slice(0,$var).css("color","yellow");
  }
  else   if($var <= 5)
  {
    $("span").slice(0,$var).css("color","green");
  }
  
  })


})
.star-rating {
  line-height:32px;
  font-size:5em;
}

.star-rating .fa-star{
    color: #28a745;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<div class="star-rating">
        <span class="fa fa-star-o star" data-rating="1" data-color="red"></span>
        <span class="fa fa-star-o star" data-rating="2"></span>
        <span class="fa fa-star-o star" data-rating="3"></span>
        <span class="fa fa-star-o star" data-rating="4"></span>
        <span class="fa fa-star-o star" data-rating="5"></span>
        <input type="hidden" name="whatever1" class="rating-value" value="4.0">
      </div>

答案 1 :(得分:0)

您可以使用CSS和jQuery这样做 Use this fiddlehttps://jsfiddle.net/gn7xvzm2/