<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>calculator</title>
<style type="text/css">
table input{
width:50px;
height:100%;
}/*button size*/
#screen{
width:150px;
height:45px;
}/* screen size*/
table,td,th {
border:1px solid #281594;
}
th{
background-color:aliceblue;
color:aquamarine;
}
</style>
<script type="text/javascript">
function add(click){
document.getElementById("screen").value += click.value;
}
function equal(){
var equation=document.getElementById("screen").value;
var ope,num1,num2;
if((ope=equation.indexOf("+"))!=-1){
num1 = parseFloat(equation.substring(0,ope));
num2 = parseFloat(equation.substring(ope+1));
document.getElementById("screen").value = num1 + num2;
}
else if((ope = equation.indexOf("-"))!=-1){
num1=parseFloat(equation.substring(0,ope));
num2 = parseFloat(equation.substring(ope+1));
document.getElementById("screen").value= num1 - num2;
}
else if((ope = equation.indexOf("*"))!=-1){
num1 = parseFloat(equation.substring(0,ope));
num2 = parseFloat(equation.substring(ope+1));
document.getElementById("screen").value = num1 * num2;
}
else if((ope.indexOf("/"))!=-1){
num1 = parseFloat(equation.substring(0,ope));
num2 = parseFloat(equation.substring(ope+1));
document.getElementById("screen").value = num1/ num2;
}
}
function clears(){
document.getElementById("screen").value ="";
}
</script>
</head>
<body>
<table >
<tr>
<th colspan = "3"><input type= "text" id = "screen"/></th>
<th><input type="button" value="clear" onclick="clears()"/></th>
</tr>
<tr>
<th><input type = "button" value = "1" onclick = "add(this)"/> </th>
<th><input type = "button" value = "2" onclick = "add(this)"/></th>
<th><input type = "button" value = "3" onclick = "add(this)"/></th>
<th><input type = "button" value = "+" onclick = "add(this)"/></th>
<!--函数和value不要重名不然会出现编译错误-->
</tr>
<tr>
<th><input type = "button" value = "4" onclick = "add(this)"/> </th>
<th><input type = "button" value = "5" onclick = "add(this)"/></th>
<th><input type = "button" value = "6" onclick = "add(this)"/></th>
<th><input type = "button" value = "-" onclick = "add(this)"/></th>
</tr>
<tr>
<th><input type = "button" value = "7" onclick = "add(this)"/> </th>
<th><input type = "button" value = "8" onclick = "add(this)"/></th>
<th><input type = "button" value = "9" onclick = "add(this)"/></th>
<th><input type = "button" value = "*" onclick = "add(this)"/></th>
</tr>
<tr>
<th><input type = "button" value = "0" onclick = "add(this)"/> </th>
<th><input type = "button" value = "." onclick = "add(this)"/></th>
<th><input type = "button" value = "=" onclick = "equal()"/></th>
<th><input type = "button" value = "+" onclick = "add(this)"/></th>
</tr>
</table>
</body>
</html>
评论0