js五角星评分
Shay_Liu 人气:0利用原生Javascript实现五角星评分,可以打半分.话不多说先上代码。
html部分
<div class="setStarRate"> <div class="star"> <span id="star"> <li> <a href="javascript:void(0)" οnclick="rateStar(1)"></a> <a href="javascript:void(0)" οnclick="rateStar(2)"></a> </li> <li> <a href="javascript:void(0)" οnclick="rateStar(3)"></a> <a href="javascript:void(0)" οnclick="rateStar(4)"></a> </li> <li> <a href="javascript:void(0)" οnclick="rateStar(5)"></a> <a href="javascript:void(0)" οnclick="rateStar(6)"></a> </li> <li> <a href="javascript:void(0)" οnclick="rateStar(7)"></a> <a href="javascript:void(0)" οnclick="rateStar(8)"></a> </li> <li> <a href="javascript:void(0)" οnclick="rateStar(9)"></a> <a href="javascript:void(0)" οnclick= "rateStar(10)"></a> </li> </span> </div> <div class="grade"> <span id="getStarRate">0.0</span> </div> </div>
CSS部分:
<style> .grade span { margin-left: 15px; line-height: 30px; } span { width: 50%; height: 70%; padding: 0; margin: 0 25%; } span li { width: 20px; height: 20px; display: inline-block; background: url("") no-repeat;//这里输入灰色状态星星的图片链接 } span li a { height: 20px; width: 10px; display: inline-block; display: block; float: left; } </style>
js部分
function rateStar(index) { var star = document.getElementById('star'); var items = star.getElementsByTagName("li"); index = parseInt(index) - 1; //因为一个星星由2个a标签组成的,所以减掉1 var tem = -1; //遍历所有的li标签 for (var i = 0; i < items.length; i++) { if (index > i * 2) { //当index大于i*2的时候,就填充i个数量的满格星星 items[i].style.background = "url() no-repeat"; items[i].style.backgroundSize = "100% 100%"; } else { if (tem == -1) { tem = i; } items[i].style.background = "url() no-repeat"; //填充灰色状态的星星 items[i].style.backgroundSize = "100% 100%"; } } //判断index是否等于偶数 if (index == parseInt(tem) * 2) { //当前li元素的背景设置成半格星星状态 items[tem].style.background = "url() no-repeat"; items[tem].style.backgroundSize = "100% 100%"; } document.getElementById('getStarRate').innerHTML = (parseInt(index) + 1) * 0.5; },
运行结果:
加载全部内容