我们经常看到淘宝、虾米音乐上的星星评价条,但是一般情况下它们都是只支持整颗星评价,如果要半颗星为单位进行评价是怎么做的呢,下面就来看一下。
首先,附上这段的源码,使用jquery:
<!DOCTYPE html>
<html>
<head>
<title>星星评价</title>
<meta charset='UTF-8'>
<style>
/*该部分为背景设置*/
div{
padding-left: 100px;
padding-top: 50px;
background: rgba(208, 118, 118, 0.1);
width: 300px;
height: 100px;
}/*该部分为背景*/
i{
display: inline-block;
width: 8px;
height: 16px;
margin: 0px;
padding: 0px;
float: left;
}
/*这里的background是半颗空的星星*/
.level_hollow_left{
background:url("./img/star_hollow_left.png") no-repeat;
}
.level_hollow_right{
background:url("./img/star_hollow_right.png") no-repeat;
}
/*这里的background是半颗实的星星*/
.level_entity_left{
background:url("./img/star_entity_left.png") no-repeat;
}
.level_entity_right{
background:url("./img/star_entity_right.png") no-repeat;
}
</style>
</head>
<body>
<div>
<span class="level star">
<i class="level_hollow_left" cjmark=""></i>
<i class="level_hollow_right" cjmark=""></i>
<i class="level_hollow_left" cjmark=""></i>
<i class="level_hollow_right" cjmark=""></i>
<i class="level_hollow_left" cjmark=""></i>
<i class="level_hollow_right" cjmark=""></i>
<i class="level_hollow_left" cjmark=""></i>
<i class="level_hollow_right" cjmark=""></i>
<i class="level_hollow_left" cjmark=""></i>
<i class="level_hollow_right" cjmark=""></i>
</span>
</div>
<script src="./jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(".star i[cjmark]").on('click',function(){
var preNum = 0;
//鼠标点击位置前面的(包括本身)置为实心,
$(this).prevAll().andSelf().each(function(i){
if(i%2==0){ //左半部分
$(this).attr('class','level_entity_left');
preNum++;
}else{
$(this).attr('class','level_entity_right');
preNum++;
}
});
//后面的置为空心
$(this).nextAll().each(function(i){
if((i+preNum)%2==0){ //左半部分
$(this).attr('class','level_hollow_left');
}else{
$(this).attr('class','level_hollow_right');
}
});
});
</script>
</body>
</html>
运行结果,星星评价随鼠标点击位置不同变化,可多次点击:
这部分代码很简单,相信你一看就会明白…