百度前端学院第17-18天,计算器带异常的实现
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>简易计算器V2.0</title>
</head>
<body>
<div class="main">
<div class="calculator">
<h1>简易计算器V2.0</h1>
<div class="input-group">
<input id="first-number" type="number" value=" " placeholder="第一个数字">
<input id="second-number" type="number" value=" " placeholder="第二个数字">
</div>
<div class="button-group">
<button id="add-btn" class="btn">加</button>
<button id="minus-btn" class="btn">减</button>
<button id="times-btn" class="btn">乘</button>
<button id="divide-btn" class="btn">除</button>
</div>
<p id="result">运算结果=</p>
</div>
</div>
</body>
</html>
.main {
position: relative;
min-width: 800px;
height: 600px;
}
.calculator {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
width: 600px;
height: 300px;
padding: 6px;
border: 2px dashed gray;
background-color: yellowgreen;
}
h1 {
text-align: center;
}
.input-group {
display: flex;
justify-content: space-around
}
#first-number {
width: 180px;
height: 40px;
font-size: 24px;
border: 1px solid black;
text-align: center;
}
#second-number {
width: 180px;
height: 40px;
font-size: 24px;
border: 1px solid black;
text-align: center;
}
.button-group {
display: flex;
justify-content: space-around;
margin-top: 30px;
}
.btn {
width: 40px;
height: 35px;
}
.btn:hover {
color: blue;
}
p {
height: 40px;
font-size: 24px;
margin-top: 40px;
position: absolute;
left: 32%;
color: crimson;
line-height: 40px;
}
js
function computed(type) {
var number1 = parseInt(document.getElementById("first-number").value);
var number2 = parseInt(document.getElementById("second-number").value);
var result = document.getElementById("result");
try {
number1 = Number(number1);
number2 = Number(number2);
if (isNaN(number1)) {
throw "第一个输入框不能为空或只能输入数字!";
}
if (isNaN(number2)) {
throw "第一个输入框不能为空或只能输入数字!";
}
if (number2 == 0 && type == "divide-btn") {
throw "零不能作除数";
}
switch (type) {
case 'add-btn': {
result.innerHTML = '运算结果:' + (number1 + number2);
};
break;
case 'minus-btn': {
result.innerHTML = '运算结果:' + (number1 - number2);
};
break;
case 'times-btn': {
result.innerHTML = '运算结果:' + (number1 * number2);
};
break;
default: {
result.innerHTML = '运算结果:' + (number1 / number2);
}
}
} catch (err) {
result.innerHTML = '错误:' + err
}
}
var add_btn = document.getElementById("add-btn");
add_btn.onclick = function () {
computed("add-btn");
}
var minus_btn = document.getElementById("minus-btn");
minus_btn.onclick = function () {
computed("minus-btn");
}
var times_btn = document.getElementById("times-btn");
times_btn.onclick = function () {
computed("times-btn");
}
var divide_btn = document.getElementById("divide-btn");
divide_btn.onclick = function () {
computed("divide-btn");
}