js实现计算器
代码如下:
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.panel {
border: 4px solid #ddd;
width: 192px;
margin: 100px auto;
/*border-radius: 6px;*/
}
.panel p,
.panel input {
font-family: "微软雅黑";
font-size: 20px;
margin: 4px;
float: left;
/*border-radius: 4px;*/
}
.panel p {
width: 122px;
height: 26px;
border: 1px solid #ddd;
padding: 6px;
overflow: hidden;
}
.panel input {
width: 40px;
height: 40px;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<div class="panel">
<div>
<p id="screen"></p>
<input type="button" value="C" onclick="clean()">
<div style="clear:both"></div>
</div>
<div>
<input type="button" value="7" onclick="inputnumber(this)">
<input type="button" value="8" onclick="inputnumber(this)">
<input type="button" value="9" onclick="inputnumber(this)">
<input type="button" value="/" onclick="operate(this)">
<input type="button" value="4" onclick="inputnumber(this)">
<input type="button" value="5" onclick="inputnumber(this)">
<input type="button" value="6" onclick="inputnumber(this)">
<input type="button" value="*" onclick="operate(this)">
<input type="button" value="1" onclick="inputnumber(this)">
<input type="button" value="2" onclick="inputnumber(this)">
<input type="button" value="3" onclick="inputnumber(this)">
<input type="button" value="-" onclick="operate(this)">
<input type="button" value="0" onclick="inputnumber(this)">
<input type="button" value="." onclick="inputnumber(this)">
<input type="button" value="=" onclick="equal(this)">
<input type="button" value="+" onclick="operate(this)">
<div style="clear:both"></div>
</div>
</div>
<script type="text/javascript">
var oScreen = document.getElementById("screen");
var str = "";
var firstTemp = 0;
var secondTemp = 0;
var sym = ""; //符合
function inputnumber(num) {
str = num.value;
oScreen.innerText += str;
secondTemp = parseFloat(oScreen.innerText);
}
function operate(symbol) {
sym = symbol.value;
if(sym == "+") {
firstTemp = parseFloat(oScreen.innerText);
oScreen.innerText = "";
} else if(sym == "-") {
firstTemp = parseFloat(oScreen.innerText);
oScreen.innerText = "";
} else if(sym == "*") {
firstTemp = parseFloat(oScreen.innerText);
oScreen.innerText = "";
} else if(sym == "/") {
firstTemp = parseFloat(oScreen.innerText);
oScreen.innerText = "";
}
}
function calculation(num1, num2, s) {
switch(s) {
case "+":
endTemp = num1 + num2;
break;
case "-":
endTemp = num1 - num2;
break;
case "*":
endTemp = num1 * num2;
break;
case "/":
endTemp = num1 / num2;
break;
}
return firstTemp = endTemp;
}
function equal(eq) {
if(eq.value == "=") {
oScreen.innerText = calculation(firstTemp, secondTemp, sym);
}
}
function clean() {
firstTemp = 0;
secondTemp = 0;
sym = "";
oScreen.innerText = "";
}
</script>
</body>