JS编写的简易计算器

在这里插入图片描述
代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>javascrip</title>
		<style type="text/css">
			div{
				width: 400px;
				height: 520px;
				margin: 0 auto;
			}
			table{
				border: solid 2px #A9A9A9;
			}
			td{
				width: 90px;
				height: 70px;
				border: 0.125rem solid darkgrey;
			}
			button{
				width: 90px;
				height: 70px;
			}
			input{
				width: 400px;
				height: 100px;
				font-weight: bold;
				font-size: 50px;
			}
		</style>
		<script type="text/javascript">
			var strs = "";
			var flg = "false"; //记录之前是否计算过答案而且没有Del
			function OnClick(obj) {
				var str = obj.innerText; //当前输入的值
				var inputNum = document.getElementById("InputNum"); //已经在屏幕上的
				//如果点击Del的话,将所有内容清空。
				if(flg == "true"){
					flg = "false";
					inputNum.value = "";
					strs="";
				}
				if(str == "Del"){
					flg = "false";
					inputNum.value = "";
					strs="";
					str="";
				}
				if(str == "x") str = "*";
				if(str == "="){
					flg = "true";
					if(strs.charAt(0) == "*" || strs.charAt(0) == "/") strs = "0";
					str = eval(strs);
					strs = str + "";
					inputNum.value += "=";
				}
				strs += str;
				if(str=="+"||str=="-"||str=="x"||str=="/") inputNum.value = strs;
				else inputNum.value += str;
			}
		</script>
	</head>
	<body>
		<div>
			<table>
				<tr>
					<td colspan="4" style="height: 100px;">
						<input type="text" id="InputNum" style="text-align: right;"/>
					</td>
				</tr>
				<tr align="center">
					<td onclick="OnClick(this)"><button><h2>1</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>2</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>3</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>+</h2></button></td>
				</tr>
				<tr align="center">
					<td onclick="OnClick(this)"><button><h2>4</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>5</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>6</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>-</h2></button></td>
				</tr>
				<tr align="center">
					<td onclick="OnClick(this)"><button><h2>7</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>8</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>9</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>x</h2></button></td>
				</tr>
				<tr align="center">
					<td colspan="2" onclick="OnClick(this)"><button style="width: 190px;"><h2>0</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>.</h2></button></td>
					<td onclick="OnClick(this)"><button><h2>/</h2></button></td>
				</tr>
				<tr align="center">
					<td colspan="2" onclick="OnClick(this)"><button style="width: 190px;"><h2>Del</h2></button></td>
					<td colspan="2" onclick="OnClick(this)"><button style="width: 190px;"><h2>=</h2></button></td>
				</tr>
			</table>
		</div>
	</body>
</html>
发布了444 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zt2650693774/article/details/104622231