<!DOCTYPE html>
<html lang="en">
<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>
<div class="container">
<input type="text" name="" id="operNumA">
<select name="" id="select" onchange="selectChange()">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" name="" id="operNumB">
<span>=</span>
<input type="text" name="" id="result">
<button onclick="btnClick()">计算</button>
</div>
<script>
let operNumA = document.getElementById('operNumA');
let operNumB = document.getElementById('operNumB');
let result = document.getElementById('result');
let operSignal = document.getElementById('select');
let selectValue = operSignal.value;
function selectChange(e) {
selectValue = operSignal.value;
btnClick();
}
function btnClick() {
if (operNumA.value == '' || operNumB.value == '') {
alert('请输入操作数!');
return;
}
let a = parseFloat(operNumA.value);
let b = parseFloat(operNumB.value);
switch (selectValue) {
case '+':
result.value = a + b;
break;
case '-':
result.value = a - b;
break;
case '*':
result.value = a * b;
break;
case '/':
result.value = a / b;
break;
default:
alert('计算错误')
break;
}
}
</script>
</body>
</html>
效果图
onchange 是指控件的值发生改变且失去焦点时触发的事件
onblur 是不管值有无改变,失去焦点就触发事件