自学JavaScript的笔记(二)

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,是指当前的对象


三.案例展示
初始界面
输入表达式
计算的结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值