做一个简易计算器,效果图片
c表示清空,为一个空字符串
+/-表示该值为正还是负
%表示当前值/100
←表示退格,往前删除一个值
eval 函数是能够计算出字符串表达式或者语句的结果,把结果求出来。
代码如下
#div1{
margin:20px auto;
width:420px;
height:490px;
background-color:#E8E8E8;
border:1px solid #ccc;
border-radius:5px;
}
.div2{
width:410px;
height:60px;
border:1px solid #ccc;
margin:5px auto;
border-radius:5px;
text-align:right;
font-size:30px;
background-color:white;
padding-top:10px;
}
.div3{
width:410px;
height:60px;
margin:5px auto;
float:left;
}
.div13{
float:left;
width:70px;
height:60px;
border:1px solid #ccc;
background-color: ghostwhite;
margin-left:8px;
text-align:center;
font-size:30px;
color:deepskyblue;
border-radius:5px;
cursor:default;
padding-top:10px;
box-shadow:4px 3px 3px #CCCCCC;
}
.div133{width:160px;}
.top{margin-top:10px;margin-left:10px;}
.color{color:black;}
.top1{margin-top:20px;margin-left:10px;}
.top2{margin-top:30px;margin-left:10px;}
.top3{margin-top:40px ;margin-left:10px;}
.div23{float:left;}
.div33{float:left;}
input=document.getElementById("input");
s="";
function a(v)
{
s=s+v;
input.innerHTML=s;
}
function e(v)
{
input.innerHTML=eval(s);
}
function w(type)
{
switch(type)
{ case ' ':s='';break;
case 'opposite':s=-s;break;
case 'percent':s=s/100;break;
case 'pow':s=Math.pow(s,2);break;
case 'sqrt':s=Math.sqrt(s);break;
case 'backspace':s=s.substr(s,s.length-1);// case 'backspace':s=s.substring(0,s.length-1);
}
input.innerHTML=s;
}
这里我本来是采用的substring这个函数的,但是在计算的时候,当只留下一个值的时候,按←的时候就不起作用,但是把substring改成substr的时候就能清除的了,原因我觉得应该是这样:s=s.substring(s,s.length-1);当只剩下一个值的时候,假设s值为7,substring中的第一个参数为是,表示中国字符串的首地址,就是0,第二个参数为0,怎么取,但是换成这样是可以的s=s.substring(0,s.length-1);,但是用s=s.substr(s,s.length-1);当只剩下一个值的时候是可以清除掉的,我想应该是当第二个参数是取得个数为0的时候,就把空字符串赋给s了吧。
以上就是JS制作简易计算器的实例代码的详细内容,更多关于JS制作简易计算器的资料请关注脚本之家其它相关文章!