自己最近在学习javaScript的知识,觉得还是动手写点什么来加深印象。于是就想着写个简易的计算器。不仅能巩固自己之前学习的css知识,也能对最近学习的知识做一个巩固。
css样式如下所示:
<style type="text/css">
#showdiv{
border:solid 1px;
border-radius:10px;/*设置边框角度*/
width: 300px;
height:400px;
text-align: center;
margin: auto;/*设置居中*/
margin-top: 50px;
background-color: floralwhite;
}
/*输入框*/
input[type=text]{
margin-top:10px;
width :290px;
height: 34px;
font-size: 30px;
font-weight: 50px;
}
/*输入按钮*/
input[type=button]{
width :60px;
height: 60px;
margin-top:20px;
margin-left: 5px;
margin-right: 5px;
}
</style>
js程序的编写
<!--
声明js代码域-->
<script type="text/javascript">
function test( btn){
//获取button按钮对象value值
var num=btn.value;
//alert(num);
//将按钮的值赋值给
switch(num){
case "=":
document.getElementById("inp").value=eval(document.getElementById("inp").value);
break;
case "c":
document.getElementById("inp").value="";
break;
default:
//
document.getElementById("inp").value=document.getElementById("inp").value+num;
break;
}
}
界面的搭建
<div id="showdiv">
<input type="text" value="" id="inp" readonly="readonly"/> <br />
<input type="button" id="btn" value="1" onclick="test(this)"/>
<input type="button" id="btn" value="2" onclick="test(this)" />
<input type="button" value="3" onclick="test(this)"/>
<input type="button" value="4" onclick="test(this)" /><br />
<input type="button" value="5" onclick="test(this)" />
<input type="button" value="6" onclick="test(this)" />
<input type="button" value="7" onclick="test(this)" />
<input type="button" value="8" onclick="test(this)"/><br />
<input type="button" value="9" onclick="test(this)"/>
<input type="button" value="+" onclick="test(this)"/>
<input type="button" value="-" onclick="test(this)"/>
<input type="button" value="*" onclick="test(this)"/><br />
<input type="button" value="0" onclick="test(this)" />
<input type="button" value="/" onclick="test(this)" />
<input type="button" value="c" onclick="test(this)" />
<input type="button" value="=" onclick="test(this)" />
</div>
计算器的实现具体的数字的计算一个是点击按钮,所以将输入框设置为“readonly”,即只读状态。
实现效果如图所示:
点击“c”实现清屏操作
心得体会
可能是由于之前学的知识忘记了,写起来的时候感觉到有点吃力,功能不算完善,只能满足基本的运算。却也花费了我不少的时间。自己也会在接下来的日子里更加努力。