js怎样实现类似星级评价星级评分特效

JavaScript030

js怎样实现类似星级评价星级评分特效,第1张

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title></title>

<style type="text/css">

.active{color: #f00}

</style>

</head>

<body>

<div class="container"><span>☆</span><span>☆</span><span>☆</span><span>☆</span><span>☆</span></div>

<script src="js/jquery_1.11.3.min.js"></script>

<script>

//点击五角星看效果

var container=$('.container')

var stars=container.find('span')

stars.click(function(){

stars.removeClass('active')

var index=$(this).index()

$('.container span:lt('+(index+1)+')').addClass('active')

})

</script>

</body>

</html>

工作当中,要实现一个打分星星评价效果,网上搜罗了一个常用的方法,但发现原代码有不足之处;

1.鼠标在星星上面滑动,在未单击的情况下滑离,若干星星会变亮,正常来讲,用户不单击打分,鼠标离开后,星星都应该为灰色,不应该有黄色星星出现;

2.鼠标单击星星,效果正常,但用户无法对打分结果进行修改,从用户体验和网站友好度考虑,这是不足取的;

为了更好的完善打分效果,在原代码的基础上做了以下修改:克服了上述两点的不足。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312" />

<title>评价打分星星效果</title>

<script type="text/javascript">

function rate(obj,oEvent){

var imgSrc = 'http://image1.koubei.com/images/store/icon_star_1.gif'

var imgSrc_2 = 'http://image1.koubei.com/images/store/icon_star_2.gif'

if(obj.rateFlag) return

var e = oEvent || window.event

var target = e.target || e.srcElement

var imgArray = obj.getElementsByTagName("img")

for(var i=0i<imgArray.lengthi++){

imgArray[i]._num = i

imgArray[i].onclick=function(){

if(obj.rateFlag) return

alert(this._num+1)

var inputid=this.parentNode.previousSibling

inputid.value=this._num+1

}

}

if(target.tagName=="IMG"){

for(var j=0j<imgArray.lengthj++){

if(j<=target._num){

imgArray[j].src=imgSrc_2

} else {

imgArray[j].src=imgSrc

}

target.parentNode.onmouseout=function(){

var imgnum=parseInt(target.parentNode.previousSibling.value)

for(n=0n<imgArray.lengthn++){

imgArray[n].src=imgSrc

}

for(n=0n<imgnumn++){

imgArray[n].src=imgSrc_2

}

}

}

} else {

return false

}

}

</script>

</head>

<body>

<input type="hidden" value="0"/><p onmouseover="rate(this,event)">

<img src="http://image1.koubei.com/images/store/icon_star_1.gif" title="很烂" /><img src="http://image1.koubei.com/images/store/icon_star_1.gif" title="一般" /><img src="http://image1.koubei.com/images/store/icon_star_1.gif" title="还好" /><img src="http://image1.koubei.com/images/store/icon_star_1.gif" title="较好" /><img src="http://image1.koubei.com/images/store/icon_star_1.gif" title="很好" />

</p>

</body>

</html>