使用js实现计算器

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>使用js实现计算器</title>
		<style type="text/css">
		/*设置整个div的位置及外边框*/
			#cal{border: solid 1px;
			 width: 300px; 
			 height: 360px; 
			 background-color: bisque;
			 text-align: center;
			 border-radius: 10px;
			 margin: auto;/*控制页面是否居中显示,如果为居中显示,那么就会用auto*/
			margin-top: 50px;	
			 }
			 /*设置文本框样式*/
			 #data{
			 	width: 280px;
			 	height: 30px;
			 	background-color: white;
			 	font-size: 15px;
			 	margin-top: 15px;
			 	margin-left: 6.5px;
			 }
			 /*设置按钮的样式*/
			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>
		<h2>
			使用js技术实现计算器
		</h2>
		<hr />
		<div id="cal">
			<input type="text" name="" id="data" value="" />
			<input type="button" name="" id="" value="1" onclick="testMath(this.value)"/>
			<input type="button" name="" id="" value="2" onclick="testMath(this.value)"/>
			<input type="button" name="" id="" value="3" onclick="testMath(this.value)"/>
			<input type="button" name="" id="" value="4" onclick="testMath(this.value)"/><br />
			<input type="button" name="" id="" value="5" onclick="testMath(this.value)" />
			<input type="button" name="" id="" value="6" onclick="testMath(this.value)" />
			<input type="button" name="" id="" value="7" onclick="testMath(this.value)" />
			<input type="button" name="" id="" value="8" onclick="testMath(this.value)"/><br />
			<input type="button" name="" id="" value="9" onclick="testMath(this.value)" />
			<input type="button" name="" id="" value="0" onclick="testMath(this.value)" />
			<input type="button" name="" id="" value="+" onclick="testMath(this.value)" />
			<input type="button" name="" id="" value="-" onclick="testMath(this.value)" /><br />
			<input type="button" name="" id="" value="*" onclick="testMath(this.value)" />
			<input type="button" name="" id="" value="/" onclick="testMath(this.value)" />
			<input type="button" name="" id="" value="=" onclick="testMath(this.value)" />
			<input type="button" name="" id="" value="c" onclick="testMath(this.value)" /><br />
		</div>
	</body>
</html>

 

  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值