<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.divs {
width: 500px;
height: 600px;
border: 1px solid #000000;
margin: auto;
}
.divs > input {
width: 460px;
height: 45px;
margin-left: 18px;
margin-top: 10px;
font-size: 30px;
background-color: white;
text-align: right;
}
.divs > div {
width: 100px;
height: 100px;
float: left;
border: 1px solid #000000;
margin-left: 18px;
margin-top: 25px;
font-size: 40px;
line-height: 100px;
text-align: center;
user-select: none;
}
</style>
</head>
<body>
<div class="divs">
<input type="text" value="0" id="input1" disabled />
<!-- value设置初始显示为0 -->
<div class="block">7</div>
<div class="block">8</div>
<div class="block">9</div>
<div class="block">-</div>
<div class="block">4</div>
<div class="block">5</div>
<div class="block">6</div>
<div class="block">+</div>
<div class="block">1</div>
<div class="block">2</div>
<div class="block">3</div>
<div class="block">*</div>
<div class="block">C</div>
<div class="block">0</div>
<div class="block">=</div>
<div class="block">/</div>
</div>
<script>
var blocks = document.getElementsByClassName("block");
// 获取类名为blocks的内容 形成数组
var input = document.getElementById("input1");
// 获取input
var firstValue = 0,
// 用于存储中间值的变量
bool = false;
// bool 通过判断消除计算后input.value中的内容 从而使下次运算可以正常进行
var type;
// 定义计算类型(+ - * /)
//for 遍历block数组
for (var i = 0; i < blocks.length; i++) {
blocks[i].onclick = function () {
//判断this.innerHTML是否为数字
if (!isNaN(this.innerHTML)) {
//判断 当bool=true时进入,使其input.value重新归0
if (bool) {
input.value = "0";
bool = false;
}
//点击内容使其以字符串的形式累加显示到input.value中
input.value = Number(input.value +this.innerHTML).toString();
}
//当this.innerHTML不是数字时
else {
// 判断this.innerHTML是否不等于C 或 = ;即判断this.innerHTML是否为 = - * /
if (this.innerHTML !== "C" && this.innerHTML !== "=") {
firstValue = Number(input.value);
type = this.innerHTML;
input.value = "0";
}
// 点击C时的属性设置
else if (this.innerHTML === "C") {
firstValue = 0;
// 暂存区归0
type = undefined;
// type设为未定义
input.value = "0";
// input.value设置为0 ,即重新显示为0
} else {
//利用switch语句完成 = - * /运算,结果以的字符串形式统一输出
switch (type) {
case "+":
input.value = (firstValue + Number(input.value)).toString();
break;
case "-":
input.value = (firstValue - Number(input.value)).toString();
break;
case "*":
input.value = (firstValue * Number(input.value)).toString();
break;
case "/":
if (Number(input.value) === 0) input.value = "0";
else{
input.value = (firstValue / Number(input.value)).toString();
break;
}
bool = true;
// 当按下等号后 bool设置为true 进行上面的判断 使input.value="0",bool=false 进而不影响接下来的运算
}
}
};
}
</script>
</body>
</html>
效果图: