当前位置:首页 > Javascript+Css+Div实现评分效果

Javascript+Css+Div实现评分效果

点击次数:2289  更新日期:2011-01-05
\n

事实上称为控件可能有点过份,因为没有进行真正的封装,只是使用纯粹的JS+CSS+DIV实现了现在常用的评分效果。


\n

效果图:

代码写得可能不是非常精致,大家可以看看,有什么问题尽管提出,希望能更加完善它。

废话不多说,看代码吧:


\n

Html代码
<!–

\n

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

\n

–><span id=”rateStatus”>评分</span>
<span id=”ratingSaved”>评分结果!</span>
<div id=”rateMe” title=”评分“>
<a onclick=”rateIt(this)” id=”_1″ title=”较差” onmouseover=”rating(this)” onmouseout=”off(this)”></a>
<a onclick=”rateIt(this)” id=”_2″ title=”还可以” onmouseover=”rating(this)” onmouseout=”off(this)”></a>
<a onclick=”rateIt(this)” id=”_3″ title=”好” onmouseover=”rating(this)” onmouseout=”off(this)”></a>
<a onclick=”rateIt(this)” id=”_4″ title=”相当好” onmouseover=”rating(this)” onmouseout=”off(this)”></a>
<a onclick=”rateIt(this)” id=”_5″ title=”好极了” onmouseover=”rating(this)” onmouseout=”off(this)”></a>
</div>


\n

样式表
<!–

\n

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

\n

–> <style type=”text/css”>
#rateStatus{float:left; clear:both; width:100%; height:20px;}
#rateMe{ clear:both; width:100%; padding:0px; margin:0px;}
#rateMe li{float:left;list-style:none;}
#rateMe li a:hover,
#rateMe .on{background:url(star_on.gif) no-repeat;width:12px;height:12px;}
#rateMe a{float:left;background:url(star_off.gif) no-repeat;width:12px; height:12px;}
#ratingSaved{display:none;}
.saved{color:red; }
</style>


\n

JS代码
<!–

\n

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

\n

–>

var sMax; // 最大数量的星星即最大评分值
var holder; // 鼠标停留的评分控件
var preSet; // 保存了评分值(通过单击来进行评分)
var rated; //是否评分过,并保存了结果(注意此值一旦设为空,就不能再评分)

// 鼠标停留事件
function rating(num){
sMax = 0; // 默认值为0
for(n=0; n<num.parentNode.childNodes.length; n++){
if(num.parentNode.childNodes[n].nodeName == “A”){
sMax++;
}
}

if(!rated){
s = num.id.replace(“_”, ”); // 获取选中的星星的索引,这里使用_1,_2,_3,_4,_5来做为评分控件的ID,当然也有其他的方式。
a = 0;
for(i=1; i<=sMax; i++){
if(i<=s){
document.getElementById(“_”+i).className = “on”;
document.getElementById(“rateStatus”).innerHTML = num.title;
holder = a+1;
a++;
}else{
document.getElementById(“_”+i).className = “”;
}
}
}
}

// 离开事件
function off(me){
if(!rated){
if(!preSet){
for(i=1; i<=sMax; i++){
document.getElementById(“_”+i).className = “”;
document.getElementById(“rateStatus”).innerHTML = me.parentNode.title;
}
}else{
rating(preSet);
//document.getElementById(“rateStatus”).innerHTML = document.getElementById(“ratingSaved”).innerHTML;
}
}
}

// 点击进行评分
function rateIt(me){
if(!rated){
document.getElementById(“rateStatus”).innerHTML = me.title;//document.getElementById(“ratingSaved”).innerHTML + ” :: “+
preSet = me;
//rated=1; //设为1以后,就变成了最终结果,不能再修改评分结果
sendRate(me);
rating(me);
}
}

//使用Ajax或其他方式发送评分结果
function sendRate(sel){
//alert(“评分结果: “+sel.title);
}

源代码打包下载


\n

来源:http://www.cnblogs.com/drunkyong

\n