1. 程式人生 > 其它 >JavaScript寫一個星星評分程式碼

JavaScript寫一個星星評分程式碼

技術標籤:javascriptjavascript

 
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GBK">
        <style>
        *{margin:0;padding:0;list-style-type:none;}
		body{font:12px/180% Arial, Helvetica, sans-serif;}
		.star_ul li{
			text-align: center;
		    float: left;
		    margin-right: 1px;
		    width: 25px;
		    height: 22px;
		    font-size: 21px;
		    background: #DCDCDC;
		    border-radius: 5px;
		    opacity: 0.8;
		    cursor: pointer;
		}
		.box{
			margin: 10px;
			left: 35%;
		    position: absolute;
		    width: 250px;
		}
		.result{
		    margin-left: 10px;
		}
        </style>
        </head>
        <body>
        	<div class='box'>
			<span style='float:left;'>評分:</span>
			<ul class="star_ul" id='star_ul_id'>
				<li title='很差' id='1'>&#10032;</li>
				<li title='差' id='2'>&#10032;</li>
				<li title='一般' id='3'>&#10032;</li>
				<li title='好' id='4'>&#10032;</li>
				<li title='很好' id='5'>&#10032;</li>
			</ul>
			<span id='result' class='result'>請打分</span>
		</div>
        </body>
        
<script>
	var flag = false;//是否點選
	var result = document.getElementById('result');
	var star = document.getElementById('star_ul_id');
	star.onmouseover=function(e){
		var e = e || window.event;
		var target = e.target || e.srcElement;
		flag=false;//只要滑鼠移入就設定為false
		gen(target,this);
	}
	star.onmouseout=function(e){
		if(flag) return;//如果滑鼠點選選中,則不重置星星狀態
		for(var i=0;i<this.children.length;i++){
			//重置所有星星的顏色
			this.children[i].style.background='gainsboro';
		}
		result.style.color='#333333';
		result.innerText="請打分";
	}
	star.onclick=function(e){
		var e = e || window.event;
		var target = e.target || e.srcElement;
		gen(target,this);
		//設定標記為true
		flag=true;
	}
	function gen(target,obj){
		var color;
		var id = parseInt(target.id);
		//根據id來設定顏色
		switch (id){
			case 1:{
				color='#EEC15A';
				break;
			}
			case 2:{
				color='#FDB666';
				break;
			}
			case 3:{
				color='#FF8D50';
				break;
			}
			case 4:{
				color='#FE6A44';
				break;
			}
			case 5:{
				color='#E44343';
				break;
			}
		}
		var len = id<=obj.children.length?id:this.children.length;
		for(var i=0;i<len;i++){
			//設定所選星星前面所有星星的顏色、包含自己
			obj.children[i].style.background=color;
		}
		result.style.color='#c00';
		result.innerText=target.title;
	}
</script>
</html>

效果如下: