jQuery+PHP星级评分实现方法

2020-05-29 07:19:36易采站长站整理

本例实现的效果:

过渡动画显示评分操作。
及时更新平均得分和用户所评的分数。
后台限制用户重复评分操作,并在前端及时显示。
XHTML


<div class="rate">
<div class="big_rate">
<span rate="2"> </span>
<span rate="4"> </span>
<span rate="6"> </span>
<span rate="8"> </span>
<span rate="10"> </span>
<div style="width:45px;" class="big_rate_up"></div>
</div>
<p><span id="s" class="s"></span><span id="g" class="g"></span></p>
<div id="my_rate"></div>
</div>

HTML结构分为用于显示灰星星div#big_rate、亮星星div#big_rate_up、分数span#s及span#g和提示信息div#my_rate。
CSS


.rate{width:600px; margin:100px auto; font-size:14px; position:relative; padding:10px 0;}
.rate p {margin:0; padding:0; display:inline; height:40px; overflow:hidden; position:absolute;
top:0; left:100px; margin-left:140px;}
.rate p span.s {font-size:36px; line-height:36px; float:left; font-weight:bold; color:#DD5400;}
.rate p span.g {font-size:22px; display:block; float:left; color:#DD5400;}
.big_rate {width:140px; height:28px; text-align:left; position:absolute; top:3px; left:85px;
display:inline-block; background:url(star.gif) left bottom repeat-x;}
.big_rate span {display:inline-block; width:24px; height:28px; position:relative; z-index:1000;
cursor:pointer; overflow:hidden;}
.big_rate_up {width:140px; height:28px; position:absolute; top:0; left:0;
background:url(star.gif) left top;}
#my_rate{ position:absolute; margin-top:40px; margin-left:100px}
#my_rate span{color:#dd5400; font-weight:bold}

jQuery
我们先来写一个函数get_rate()来处理评分的前端交互。


function get_rate(rate){
....do some thing
}

函数get_rate(rate),需要传递一个参数:rate,用来表示平均分值。接着在函数里要处理参数rate:


rate=rate.toString();
var s;
var g;
$("#g").show();
if (rate.length>=3){
s=10;
g=0;
$("#g").hide();
}else if(rate=="0"){
s=0;
g=0;
}else{
s=rate.substr(0,1);
g=rate.substr(1,1);
}
$("#s").text(s);
$("#g").text("."+ g);

将平均分值rate转换成格式如:6.8,用于前端显示平均分。
接下来,当我们鼠标滑向星星时,会产生一个动画效果,亮星星的宽度会随着鼠标滑向变化,分数值也会随之变化。