1. 程式人生 > >JS部分練習(書寫計算器)

JS部分練習(書寫計算器)

<html>
	<head>
		<title>js的計算器案例</title>
		<meta charset="UTF-8"/>
		<!--宣告css程式碼域-->
		<style type="text/css">
		/*設定div樣式*/
			#showdiv{
				border: solid 1px;
				width: 300px;
				height: 360px;
				text-align: center;
				border-radius: 10px;
				margin: auto;
				margin-top: 50px;
				background-color: #EEE;
			}
		/*設定文字框樣式*/
			#data{
				width: 270px;
				height: 30px;
				font-size: 15px;
				margin-top: 20px;
				margin-bottom: 20px;
			}	
		/*設定按鈕的樣式*/
			input[type=button]{
				width: 55px;
				height: 55px;
				font-size: 25px;
				margin: 5px;
				background-color: #ccc;
			}	
		</style>
		<!--宣告js程式碼域-->
		<script type="text/javascript">
			//宣告計算器功能函式
				function testMath(val){
					//獲取計算器文字框物件
					var inp=document.getElementById("data");
					//使用switch實現計算器的運算
					switch (val){
						case "=":
							inp.value=eval(inp.value);
							break;
						case "c":
							inp.value="";
							break;
						default:
							inp.value=inp.value+val;
							break;
					}
				}
		</script>
	</head>
	<body>
		<div id="showdiv">
			<input type="text" name="data" id="data" value="" />
			<input type="button" id="" value="1" onclick="testMath(this.value)"/>
			<input type="button" id="" value="2" onclick="testMath(this.value)"/>
			<input type="button" id="" value="3" onclick="testMath(this.value)"/>
			<input type="button" id="" value="4" onclick="testMath(this.value)"/><br />
			<input type="button" id="" value="5" onclick="testMath(this.value)"/>
			<input type="button" id="" value="6" onclick="testMath(this.value)"/>
			<input type="button" id="" value="7" onclick="testMath(this.value)"/>
			<input type="button" id="" value="8" onclick="testMath(this.value)"/><br />
			<input type="button" id="" value="9" onclick="testMath(this.value)"/>
			<input type="button" id="" value="0" onclick="testMath(this.value)"/>
			<input type="button" id="" value="+" onclick="testMath(this.value)"/>
			<input type="button" id="" value="-" onclick="testMath(this.value)"/><br />
			<input type="button" id="" value="*" onclick="testMath(this.value)"/>
			<input type="button" id="" value="/" onclick="testMath(this.value)"/>
			<input type="button" id="" value="=" onclick="testMath(this.value)" />
			<input type="button" id="" value="c" onclick="testMath(this.value)"/>
		</div>
	</body>
</html>