js计算器案例
一.说明
该案例通过对html,css以及JavaScript的学习,设计出简单的网页版计算器,还有很多需要改进的地方,比如一些错误的输入,要有提示等等。下面是代码以及计算器的界面。
二.代码展示
<html>
<head>
<meta charset="utf-8">
<title>js计算器</title>
<!-- 声明css代码域-->
<style type="text/css">
/* 设置div样式*/
#showdiv{
border: solid 1px;
border-radius: 10px;/*设置边框弧度*/
width: 320px;
height: 370px;
margin: auto;/*设置居中*/
margin-top: 50px;
background-color: antiquewhite;
text-align: center;
}
/*设置输入框样式*/
input[type=text]{
margin-top: 20px;
width: 290px;
height: 34px;
font-size: 25px;
}
/* 设置按钮样式*/
input[type=button]{
width: 50px;
height: 50px;
margin-top: 20px;
margin-left: 5px;
margin-right: 5px;
font-size: 25px;
font-weight: bold;/*字体加粗*/
}
</style>
<!-- 声明js代码域-->
<script type="text/javascript">
//声明函数
function test (btn){
//获取button按钮对象
var num = btn.value;
//将按钮的值赋给input输入框
//根据用户点击动作执行对应的逻辑
switch(num){
//当用户点击“=”的按钮时,就计算输入框里的式子
case "=":
document.getElementById("ipn").value=eval(document.getElementById("ipn").value);//计算某个字符串
break;
//当用户点击“c”的按钮时,就将输入框清空
case "c":
document.getElementById("ipn").value="";
break;
default:
document.getElementById("ipn").value=document.getElementById("ipn").value+num;
break;
}
}
</script>
</head>
<body>
<div id="showdiv">
<input type="text" name="" id="ipn" value="" readonly><br>
<input type="button" name="" id="btn" value="1" onClick="test(this)">
<input type="button" name="" id="" value="2" onClick="test(this)">
<input type="button" name="" id="" value="3" onClick="test(this)">
<input type="button" name="" id="" value="4" onClick="test(this)"><br>
<input type="button" name="" id="" value="5" onClick="test(this)">
<input type="button" name="" id="" value="6" onClick="test(this)">
<input type="button" name="" id="" value="7" onClick="test(this)">
<input type="button" name="" id="" value="8" onClick="test(this)"><br>
<input type="button" name="" id="" value="9" onClick="test(this)">
<input type="button" name="" id="" value="+" onClick="test(this)">
<input type="button" name="" id="" value="-" onClick="test(this)">
<input type="button" name="" id="" value="*" onClick="test(this)"><br>
<input type="button" name="" id="" value="0" onClick="test(this)">
<input type="button" name="" id="" value="/" onClick="test(this)">
<input type="button" name="" id="" value="=" onClick="test(this)">
<input type="button" name="" id="" value="c" onClick="test(this)">
</div>
</body>
</html>
注意:在body中的onclick操作test()该函数传入值是this,是指当前的对象
三.案例展示