Калькулятор
Простой калькулятор на JavaScript
by alex_xpert
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="calculator">
<table>
<tr>
<td colspan="4"><div id="display"></div></td>
</tr>
<tr>
<td><button onclick="prnt(1)">1</button></td>
<td><button onclick="prnt(2)">2</button></td>
<td><button onclick="prnt(3)">3</button></td>
<td><button onclick="calc('addition')">+</button></td>
</tr>
<tr>
<td><button onclick="prnt(4)">4</button></td>
<td><button onclick="prnt(5)">5</button></td>
<td><button onclick="prnt(6)">6</button></td>
<td><button onclick="calc('subtraction')">-</button></td>
</tr>
<tr>
<td><button onclick="prnt(7)">7</button></td>
<td><button onclick="prnt(8)">8</button></td>
<td><button onclick="prnt(9)">9</button></td>
<td><button onclick="calc('multiplication')">*</button></td>
</tr>
<tr>
<td><button onclick="prnt(0)">0</button></td>
<td><button onclick="prnt('.')">.</button></td>
<td><button onclick="result()">=</button></td>
<td><button onclick="calc('division')">/</button></td>
</tr>
<tr>
<td colspan="4"><button onclick="reset()">Сброс</button></td>
</tr>
</table>
</div>
</body>
</html>
CSS
#calculator {
width:145px;
height: 170px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -75px;
margin-top: -125px;
text-align: center;
border: 1px solid #C0C0C0;
padding: 5px;
}
#display {
width: 138px;
height: 20px;
background-color: #F5F5F5;
border: 1px solid #C0C0C0;
text-align: right;
}
JavaScript
var operand = null;
var operation = null;
function prnt(c) {
document.getElementById("display").innerHTML = document.getElementById("display").innerHTML + c;
}
function calc(o) {
operand = document.getElementById("display").innerHTML;
operation = o;
document.getElementById("display").innerHTML = "";
}
function result() {
if (operand === null || operation === null || document.getElementById("display").innerHTML === "") {
alert("Нечего считать!");
return;
}
other_operand = document.getElementById("display").innerHTML - 0;
r = 0;
switch (operation) {
case "addition":
r = +operand + other_operand;
break;
case "subtraction":
r = operand - other_operand;
break;
case "multiplication":
r = operand * other_operand;
break;
case "division":
r = operand / other_operand;
break;
}
document.getElementById("display").innerHTML = r;
}
function reset() {
document.getElementById("display").innerHTML = "";
operand = null;
operation = null;
}