<html>
<head>
<title>js的计算器案例</title>
<meta charset="UTF-8"/>
<!--声明css代码域-->
<style type="text/css">
/*设置div样式*/
#showdiv{
border: solid 1px;
width: 300px;
height: 360px;
text-align: center;
border-radius: 10px;
margin: auto;
margin-top: 50px;
background-color: #EEE;
}
/*设置文本框样式*/
#data{
width: 270px;
height: 30px;
font-size: 15px;
margin-top: 20px;
margin-bottom: 20px;
}
/*设置按钮的样式*/
input[type=button]{
width: 55px;
height: 55px;
font-size: 25px;
margin: 5px;
background-color: #ccc;
}
</style>
<!--声明js代码域-->
<script type="text/javascript">
//声明计算器功能函数
function testMath(val){
//获取计算器文本框对象
var inp=document.getElementById("data");
//使用switch实现计算器的运算
switch (val){
case "=":
inp.value=eval(inp.value);
break;
case "c":
inp.value="";
break;
default:
inp.value=inp.value+val;
break;
}
}
</script>
</head>
<body>
<div id="showdiv">
<input type="text" name="data" id="data" value="" />
<input type="button" id="" value="1" onclick="testMath(this.value)"/>
<input type="button" id="" value="2" onclick="testMath(this.value)"/>
<input type="button" id="" value="3" onclick="testMath(this.value)"/>
<input type="button" id="" value="4" onclick="testMath(this.value)"/><br />
<input type="button" id="" value="5" onclick="testMath(this.value)"/>
<input type="button" id="" value="6" onclick="testMath(this.value)"/>
<input type="button" id="" value="7" onclick="testMath(this.value)"/>
<input type="button" id="" value="8" onclick="testMath(this.value)"/><br />
<input type="button" id="" value="9" onclick="testMath(this.value)"/>
<input type="button" id="" value="0" onclick="testMath(this.value)"/>
<input type="button" id="" value="+" onclick="testMath(this.value)"/>
<input type="button" id="" value="-" onclick="testMath(this.value)"/><br />
<input type="button" id="" value="*" onclick="testMath(this.value)"/>
<input type="button" id="" value="/" onclick="testMath(this.value)"/>
<input type="button" id="" value="=" onclick="testMath(this.value)" />
<input type="button" id="" value="c" onclick="testMath(this.value)"/>
</div>
</body>
</html>
JS部分练习(书写计算器)
猜你喜欢
转载自blog.csdn.net/wyqwilliam/article/details/83759111
今日推荐
周排行