<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>计算器</title>
<style type="text/css">
.button{width: 80px; height: 30px;}
</style>
</head>
<body>
<input type="text" id="txt-display" value="0" style="text-align: right; width: 400px;"/>
<script type="text/javascript">
//定义一个数组
calc_btns=[0,1,2,3,4,5,6,7,8,9,".","=","+","-","*","/","AC","sin","cos","tan","asin","acos","atan","ln"];
//定义三个全局变量
var op="",syb=0,start_new_input=true;//op运算符,syb上一步,start_new_input是否清空
//定义一个方法向页面添加按钮
function write_table()
{
document.write("<table>")
document.write("<tr>")
for(var i=0;i<calc_btns.length;i++)
{
document.write("<td><input onclick='calc(this.value)' class='button' type='button' value='"+calc_btns[i]+"' ></td>")
if((i+1)%5==0)
{
document.write("<tr></tr>")
}
}
document.write("</tr>")
document.write("</table>")
}
//定义一个方法,计算
function calc(strcmd)//strcmd:用于接收用户在点击按钮时传递过来的value值---this指示的是当前--this.value
{
//因为求的值都需在文本框显示所以获取文本框
var txtdisplay=document.getElementById("txt-display")
switch (strcmd){
//三角函数直接对应的有数学对象
case "sin":txtdisplay.value=Math.sin(txtdisplay.value);
break;
case "cos":txtdisplay.value=Math.cos(txtdisplay.value);
break;
case "tan":txtdisplay.value=Math.tan(txtdisplay.value);
break;
case "asin":txtdisplay.value=Math.asin(txtdisplay.value);
break;
//四则运算+-*/=ac
case "+":
case "-":
case "*":
case "/":
//计算公式 文本框= 上一步+运算符+当前值
start_new_input=true
if(op!="" && txtdisplay.value!="")
{
txtdisplay.value=eval(syb+op+txtdisplay.value);
op=strcmd
}
else
{
op=strcmd
}
break;
//=
case "=":
start_new_input=true
if(op!="" && txtdisplay.value!="")
{
txtdisplay.value=eval(syb+op+txtdisplay.value)
op=strcmd
}
op="";
syb=0
break;
case "AC":
op=""
txtdisplay.value="0"
syb=0
start_new_input=true
break;
//小数点进行定义--小数点只能出现一次
//调用字符串的indexof方法进行查找,如果当前输入已经有小数点则跳出操作
case ".":
if(txtdisplay.value.indexOf(".")!=-1)
{
break
}
default:
//如果需要清空原有的输入,则将原有输入保存在上一步中,并将需要清空原有输入状态为false
if(start_new_input)
{
start_new_input=false;
syb=txtdisplay.value
txtdisplay.value="0"
}
//如果我们输入的内容不是0,把当前内容赋值给文本框
if(txtdisplay.value!="0")
{
txtdisplay.value+=strcmd;
}
else if(strcmd!="0")
{
txtdisplay.value=strcmd
}
break;
}
}
//用于计算的方法
write_table()
</script>
</body>
</html>
制作一个计算器
最新推荐文章于 2021-12-20 21:38:31 发布