1. 程式人生 > >JavaScript學習:計算器-heml+css+javascript功能的實現

JavaScript學習:計算器-heml+css+javascript功能的實現

介面 html程式碼:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>計算器-最終形態</title>
		<script src="../js/demo06.js"></script>
		<link rel="stylesheet" href="../css/demo06.css" /> 
	</head>
	<body>
		<div class="outside">
			<!--外部-->
			<div class="button">
				<div id="but1">●</div>
				<div id="but2">●</div>
				<div id="but3">●</div>
			</div>
			<div class="show" id="shows">					
			</div>
			<div class="keyboard" id="abc">
				<div onclick="getAc();">AC</div>
				<div onclick="getBack();">+/-</div>
				<div onclick="getNum('%');">%</div>
				<div onclick="getNum('/');">&divide;</div>
				<div onclick="getNum(7);">7</div>
				<div onclick="getNum(8);">8</div>
				<div onclick="getNum(9);">9</div>
				<div onclick="getNum('*');">&times;</div>
				<div onclick="getNum(4);">4</div>
				<div onclick="getNum(5);">5</div>
				<div onclick="getNum(6);">6</div>
				<div onclick="getNum('-');">-</div>
				<div onclick="getNum(1);">1</div>
				<div onclick="getNum(2);">2</div>
				<div onclick="getNum(3);">3</div>
				<div onclick="getNum('+');">+</div>
				<div onclick="getNum(0);">0</div>
				<div onclick="delLast();">刪除</div>
				<div onclick="getNum('.');">.</div>
				<div onclick="getResult();">=</div>
			</div>			
		</div>
	</body>
</html>

css程式碼:

.outside {
	width: 400px;
	height: 425px;
	background-color: darkgray;
	margin: 0 auto;
	border-top-left-radius: 10px;
	border-top-right-radius: 10px;
}

.button {
	width: 400px;
	height: 50px;
	margin: 0 auto;
}

#but1 {
	width: 30px;
	color: red;
	font-size: 30px;
	float: left;
}

#but2 {
	width: 30px;
	color: yellow;
	font-size: 30px;
	float: left;
}

#but3 {
	width: 30px;
	color: blue;
	font-size: 30px;
	float: left;
}

.show {
	width: 390px;
	height: 50px;
	background-color: white;
	border: solid 2px red;
	margin: 0 auto;
	text-align: right;
	line-height: 50px;
	color: black;
	font-size: 40px;
}

#abc div {
	width: 96px;
	height: 60px;
	float: left;
	background-color: aqua;
	margin: 2px;
	text-align: center;
	line-height: 60px;
	font-size: 25px;
	border-radius: 5px;
}

#abc div:hover {
	background-color: orangered;
}

js程式碼:

function getNum(num){
	document.getElementById("shows").innerHTML += num;
}

function getResult(){
	var express = document.getElementById("shows").innerHTML;
	var result = eval(express);
	document.getElementById("shows").innerHTML = result
}

function getAc(){
	document.getElementById("shows").innerHTML = "";
}

function delLast(){
	var express = document.getElementById("shows").innerHTML;
	var newNum = express.substring(0,express.length-1);
	document.getElementById("shows").innerHTML = newNum;
}

function getBack(){
	var express = document.getElementById("shows").innerHTML;
	var newNum = 0 - eval(express);
	document.getElementById("shows").innerHTML = newNum;
}