js实现简易计算器

js实现简易计算器 为每个按钮绑定点击事件并将值赋给input 在使用eval方法计算input中的值 同时也使用slice方法实现退格删除字符功能

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>简易计算器</title>
		<style type="text/css">
			*{
				margin: 0;
				padding: 0;
			}
			.dome{
				width: 400px;
				height: 430px;
				margin: 50px auto;
				background: #CCCCCC;
				padding: 20px;
			}
			.dome>input{
				width:100%;
				height: 50px;
				font-size: 24px;
			}
			.dome>.main{
				margin-top: 30px;
			}
			.dome>.main>button{
				outline: none;
				border: none;
				flex-grow: 1;
				font-size: 18px;
				width: 90px;
				height: 60px;
				margin:5px;
				float: left;
				background: white;
				text-align: center;
				line-height: 60px;
			}
			.dome>.main>button:active{
				border: 3px solid #CCCCFF;
			}/*点击按钮时*/
			
		</style>
		
	</head>
	<body>
		<div class="dome">
			<input type="text" value="" id="ipt">
			<div class="main">
				<button onclick="addcount(this.innerText)">7</button>
				<button onclick="addcount(this.innerText)">8</button>
				<button onclick="addcount(this.innerText)">9</button>
				<button onclick="BKSP()">←</button>
				
				
				<button onclick="addcount(this.innerText)">4</button>
				<button onclick="addcount(this.innerText)">5</button>
				<button onclick="addcount(this.innerText)">6</button>
				<button onclick="addcount('/')">÷</button>
				
				
				<button onclick="addcount(this.innerText)">1</button>
				<button onclick="addcount(this.innerText)">2</button>
				<button onclick="addcount(this.innerText)">3</button>
				
				<button onclick="addcount('*')">x</button>
				
				<button onclick="addcount('%')">%</button>
				<button onclick="addcount(this.innerText)">0</button>
				<button onclick="addcount(this.innerText)">.</button>
				<button onclick="addcount(this.innerText)">+</button>
				
				
				<button onclick="Clear()">AC</button>
				<button onclick="addcount('-')">-</button>
				<button onclick="result()" style="width: 190px;background: #333333;color: white;">=</button>
			</div>
	
		</div> 
		<script type="text/javascript"> 
		var ipt=document.getElementById("ipt");
				function addcount(s){//点击后将按钮的值返回到输入框上
					ipt.value+=s;
				}
				function result(){//点击等于计算结果
					ipt.value=eval(ipt.value);//把输入框的内容当作值计算
				}
				function Clear(){//清除输入框的内容
					ipt.value="";
				}
				function BKSP(){//退格截取字符串
					ipt.value=ipt.value.slice(0,ipt.value.length-1);//截取字符串并赋值给输入框
				}
		</script>
	</body>
	
</html>

效果如下:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值