直接上传代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>网页版计算器</title>
<style>
input{
width: 397px;
height: 50px;
font-size: 30px;
}
tr{
text-align: center;
}
td{
width: 100px;
height: 119px;
font-size: 30px;
}
td:hover{
background-color: greenyellow;
cursor: pointer;
}
</style>
</head>
<body>
<center><input type="text" value="0" disabled="disabled" id="show"/></center>
<table border="1px" cellspacing="0" cellpadding="0" width="400px" height="600px" align="center">
<tr>
<td id="clear">C</td>
<td id="del">退格</td>
<td class="operator">%</td>
<td class="operator">/</td>
</tr>
<tr>
<td class="num">7</td>
<td class="num">8</td>
<td class="num">9</td>
<td class="operator">*</td>
</tr>
<tr>
<td class="num">4</td>
<td class="num">5</td>
<td class="num">6</td>
<td class="operator">-</td>
</tr>
<tr>
<td class="num">1</td>
<td class="num">2</td>
<td class="num">3</td>
<td class="operator">+</td>
</tr>
<tr>
<td colspan="2" class="num">0</td>
<td class="num">.</td>
<td id="result">=</td>
</tr>
</table>
</body>
<script>
var showresult = document.getElementById("show");
var clear = document.getElementById("clear");
var del = document.getElementById("del");
var result = document.getElementById("result");
var nums = document.getElementsByClassName("num");
var numvalue1 = "";
var numvalue2 = "";
var oper = "";
for(var i=0; i<nums.length; i++){
nums[i].onclick = function(){
numvalue1 += this.innerText;
showresult.value = numvalue1;
}
}
var operators = document.getElementsByClassName("operator");
for(var i=0; i < operators.length; i++){
operators[i].onclick = function(){
if(numvalue2 == ""){
numvalue2 = numvalue1;
numvalue1 = "";
oper = this.innerText;
} else{
if(numvalue1 != ""){
resultFn();
}
oper = this.innerText;
}
}
}
clear.onclick = function(){
numvalue1 = "";
numvalue2 = "";
oper = "";
showresult.value = 0;
}
del.onclick = function(){
if(numvalue1.length >=1){
numvalue1 = numvalue1.substring(0,numvalue1.length-1);
showresult.value = numvalue1;
}
}
result.onclick = function(){
resultFn();
}
function resultFn(){
var one = new Number(numvalue2);
var two = new Number(numvalue1);
var r = null;
switch(oper){
case "+":
r = one + two;
break;
case "-":
r = one - two;
break;
case "*":
r = one * two;
break;
case "/":
if(two == 0){
r = 0;
} else{
r = one / two;
}
break;
case "%":
if(two == 0){
r = 0;
} else {
r = one % two;
}
break;
default:
alert("输入有误");
}
numvalue2 = new Number(r).toFixed(6);
numvalue1 = "";
showresult.value = numvalue2*1;
}
</script>
</html>