复制Yelp星级审核小部件

时间:2015-08-16 19:23:36

标签: javascript css3

我试图复制yelp.com上的星级评级小部件 - 5星评级小部件当你将鼠标悬停在下一颗星上时,所有之前的星星都会改变颜色以匹配活跃的星星。还需要一个悬停状态,显示星级的描述。

您可以在此处查看小部件: https://www.yelp.com/writeareview/biz/C5SIHa89RV4Gw05zD8vLQg?return_url=%2Fwriteareview%2Fsearch%3Fwar_desc%3Dtacos%26war_loc%3DAustin%252C%2BTX

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

在没有JS的情况下编造了一些结果:

.stars{
  displaY:inline-block;
  position:relative;
}
.stars span{
  color:#999;
  displaY:inline-block;
  vertical-align:middle;
  float:right;
  cursor:pointer;
}
.stars>span:hover:after{
  position:absolute;
  content: attr(title);
  left:100%;
}

.stars>span:nth-child(1):hover,
.stars>span:nth-child(1):hover ~ span{color: red;}
.stars>span:nth-child(2):hover,
.stars>span:nth-child(2):hover ~ span{color: #f73;}
.stars>span:nth-child(3):hover,
.stars>span:nth-child(3):hover ~ span{color: #fa2;}
.stars>span:nth-child(4):hover,
.stars>span:nth-child(4):hover ~ span{color: #eb2;}
.stars>span:nth-child(5):hover,
.stars>span:nth-child(5):hover ~ span{color: #d92;}
<div class="stars">
  <span title="WOW">&#9733;</span>
  <span title="LOL">&#9733;</span>
  <span title="Yey">&#9733;</span>
  <span title="Hmm">&#9733;</span>
  <span title="Boo">&#9733;</span>
</div>

现在在JS或jQuery中,您只需要分配一个active类并将投票提交给服务器(例如 jsBin demo )。

修改

由于以上可能有点错误(“谢谢”CSS)这里主要是JS(jQuery)示例:

var msg = ["Hover and Click to rate!","Boo","Hmm","Yey","LOL","WOW"];

$("[data-stars]").each(function(){
  
  var $el = $(this);
  var h   = $el.height();
  var w   = $el.width();
  var old = $el.data("stars");
  var now;
  var $info = $("<span/>");  
  $el.append($info);

  function setStars( val ){
    $el.attr("data-stars", val);
    $info.text( msg[val] );
  }
  setStars( old );
  
  $el.on("mousemove", function(e){
    now = (e.pageX-$(this).offset().left)/w*5 +1|0;
    setStars( now );
  }).on("mouseleave", function(){
    setStars( old );
  }).on("click", function(){
    old = now;
    setStars( old );
    // Submit `old` string value ("1-5") to server using AJAX 
  });
  
});
[data-stars]{
  display:inline-block;
  vertical-align:middle;
  position:relative;
  height:30px;
  width:150px;
  background:url(http://i.stack.imgur.com/ZpQ8g.png) 0 0 / cover;
}
[data-stars]>span{
  position:absolute;
  white-space:nowrap;
  left:100%;
  top:9px;
}
[data-stars="0"]{background-position:0    0px;}
[data-stars="1"]{background-position:0  -30px;}
[data-stars="2"]{background-position:0  -60px;}
[data-stars="3"]{background-position:0  -90px;}
[data-stars="4"]{background-position:0 -120px;}
[data-stars="5"]{background-position:0 -150px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-stars=0></div><br>
<div data-stars=2></div><br>
<div data-stars=5></div><br>
<div data-stars=4></div>