需求:兩個輸入框預設值 123123,頁面加載即顯示商,輸入時實時更新,無需失去焦點。
| 事件 | 觸發時機 | 適用場景 |
|---|---|---|
onchange | 元素失去焦點且值已改變 | 表單提交前驗證 |
oninput | 值發生變化即刻觸發(輸入、粘贴、拖拽) | 實時預覽、即時計算 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>實時除法計算器</title>
<script>
function compute() {
var a = parseFloat(document.getElementById("txt1").value) || 0;
var b = parseFloat(document.getElementById("txt2").value) || 0;
if (b !== 0) {
document.getElementById("txt3").value = (a / b).toFixed(2);
} else {
document.getElementById("txt3").value = "除數不能為0";
}
}
// 頁面加載初始化
window.onload = function() {
compute();
};
</script>
</head>
<body>
<input type="text" id="txt1" value="123123" oninput="compute()"> ÷
<input type="text" id="txt2" value="123123" oninput="compute()"> =
<input type="text" id="txt3" readonly>
</body>
</html>
compute 內用 setTimeout / requestAnimationFrame 節流。input 事件配合 pattern 屬性或 JS 正則,限制只能輸入數字。addEventListener('input', compute) 替代內聯屬性,結構行為分離。掌握 oninput 与 onload 配合,即可構建流暢的實時計算表單。