JS实现星级评分——简化版

过了一段时间,再次来实现星级评分,做了一定的简化,运用了函数传参、三目运算来实现简化。

HTML代码:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>星级评分</title>
	<style type="text/css">
		body{
			background: #e898ba66;
		}
		.pingfen{
			width: 460px;
			height: 200px;
			background: #fff;
			margin: 150px auto;
			border-radius: 5px;
		}
		.header{
			width: 100%;
			height: 70px;
			border-bottom: 1px solid rgb(225, 86, 113);
			font-size: 30px;
			color: rgb(225, 86, 113);
			font-weight: bolder;
			text-align: center;
			line-height: 72px;


		}
		.content{
			width: 100%;
			height: 72px;
		}
		.stars{
			width: 50%;
			list-style: none;
			margin: 0;
			line-height: 67px;
			color: #ccc;
			margin-left: 30px;
			float: left;
		}
		.stars span{
			font-size: 30px;
			margin-left: 10px;
		}
		.stars span:after{
			content: '☆';
		}
		.stars .show:after,.stars .show2:after{
			content: '★';
		}
		.info{
			float: left;
			width: 60px;
			height: 30px;
			background: #e15671;
			border-radius: 5px;
			color: #fff;
			margin-top: 21px;
			text-align: center;
			line-height: 30px;
			display: none;
		}
		.tips{
			width: 100%;
			height: 58px;
			background: rgb(225, 86, 113);
			color: #fff;
			line-height: 58px;
			text-align: center;
		}
		.show {
				color: #e4c6e4;
			}
		.show2{
			color: #e15671; 
		}
	</style>
</head>
<body>
<div class="pingfen">
	<div class="header">
		总体评价
	</div>
	<div class="content">
		<div class="stars">
			<span></span>
			<span></span>
			<span></span>
			<span></span>
			<span></span>
		</div>
		<div class="info">优秀</div>
	</div>
	<div class="tips">小提示:点击星星就能打分
	</div>
</div></body>
</html>

效果图:


JS代码:

<script type="text/javascript">
	var stars=document.querySelectorAll('.stars span');
	var info=document.querySelector('.info');
	var grades = ["极差","差","一般","良好","优秀"];
	var active=-1;   //记录当前点击的是哪颗星星

	for(var i=0;i<stars.length;i++){
		stars[i].index=i;
		stars[i].onmouseover=function(){setStar(this.index);};
		stars[i].onmouseout=function(){setStar(active);};
		stars[i].onclick=setClick;
	}

	function setStar(nub){
		var name='';
		name= nub<2?'show':'show2';
		for(var i=0;i<stars.length;i++){
			stars[i].className= i<=nub?name:'';
		}
		info.style.display= nub<0? 'none':'block';
		info.innerHTML=grades[nub];
	}

	function setClick(){
		active=this.index;
	}
</script>

效果图:




猜你喜欢

转载自blog.csdn.net/qq_34446663/article/details/80193415