<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<fieldset onload="init()">
<legend>小小计算器</legend>
<input type="number" name="n1" id="n1" value="0" oninput="calcu()" />
<select name="" id="opt" oninput="calcu()">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" name="n2" id="n2" value="0" oninput="calcu()" />
<span>=</span>
<span class="res">0</span>
</fieldset>
<script>
const n1 = document.querySelector(“#n1”);
const n2 = document.querySelector(“#n2”);
const opt = document.querySelector(“#opt”);
function init() {
n1.value = 0;
n2.value = 0;
opt.value = "+";
}
function calcu() {
let value1 = n1.value * 1;
let value2 = n2.value * 1;
let optType = opt.value;
let res = 0;
switch (optType) {
case "+":
res = value1 + value2;
break;
case "-":
res = value1 - value2;
break;
case "*":
res = value1 * value2;
break;
case "/":
if (value2 === 0) throw "除数不能为零";
res = (value1 / value2).toFixed(2);
break;
default:
throw "非法操作";
}
document.querySelector(".res").textContent = res;
}
</script>
</body>
</html>