您现在的位置是:首页 > 技术杂文前端杂文

原生JS实现星星打分

阿龙2022-05-17【前端杂文】人已围观

CSS
.wrapper{width:300px; margin:10px auto; font:14px/1.5 arial;}
/*tab*/
#star{overflow:hidden;}
#star li{
float:left;
width:20px;
height:20px;
margin:2px;
display:inline;
color:#999;
font:bold 18px arial;
cursor:pointer
}
#star .act{
color:red
}
#star_word{
width:80px;
height:30px;
line-height:30px;
border:1px solid #ccc;
margin:10px;
text-align:center;
display:none
}
JS
window.onload = function(){
	var star = document.getElementById("star");
	var star_li = star.getElementsByTagName("li");
	var star_word = document.getElementById("star_word");
	var result = document.getElementById("result");
	var i=0;
	var j=0;
	var len = star_li.length;
	var word = ['很差','差','一般',"好","很好"]
	for(i=0; i<len; i++){
		star_li[i].index = i;
		star_li[i].onclick = function(){
			star_word.style.display = "block";
			star_word.innerHTML = word[this.index];
			for(i=0; i<star_li.length; i++){
				if (i <= this.index) {
					star_li[i].className = "act";
				} else {
					star_li[i].className = ''
				}
			}
			result.innerHTML = (this.index+1)+"分";	
		}
 	}
}
html
<div class="wrapper">
打分结果 
<span id="result"></span>
<ul id="star">
<li>★</li>
<li>★</li>
<li>★</li>
<li>★</li>
<li>★</li>
</ul>
<div id="star_word">一般</div>
</div> 
效果如下:

Tags:

很赞哦! ()