首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript 實現簡易計算器:數字按鍵顯示到文本框完整教程

     編輯:程式設計綜合問答

項目目標

構建一個基於 HTML/CSS/JavaScript 的網頁計算器,實現數字按鈕點擊後將數字追加顯示在頂部輸入框,支持四則運算、清除、退位、平方等功能。

核心邏輯設計

  1. 狀態管理:用全局變量儲存當前輸入值(val)、首個操作數(temp)、運算符(oper)。
  2. 事件分發:
    - 數字鍵調用 inputEvent(this) 追加顯示
    - 運算符鍵調用 inputOper(this) 暫存操作數並清空輸入框
    - 等號鍵調用 inputEquel(this) 執行計算並顯示結果
    - 功能鍵(Clear、Back、平方)調用 inputPCB(this)
  3. 計算引擎:封裝 Calculator 類,jisuan(num1, num2, oper) 通過 switch 執行具體運算。

完整可運行代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS 計算器</title>
<style>
  input[type=button] { width: 60px; height: 40px; font-size: 18px; }
  #display { width: 280px; height: 40px; text-align: right; font-size: 20px; padding: 5px; }
  table { border-collapse: collapse; margin: 20px auto; }
  td { padding: 5px; }
</style>
</head>
<body>
<table>
  <tr><td colspan="4"><input id="display" type="text" readonly></td></tr>
  <tr>
    <td><input type="button" value="x²" onclick="handleFunc(this)"></td>
    <td><input type="button" value="C" onclick="handleFunc(this)"></td>
    <td><input type="button" value="<--" onclick="handleFunc(this)"></td>
    <td></td>
  </tr>
  <tr>
    <td><input type="button" value="7" onclick="inputNum(this)"></td>
    <td><input type="button" value="8" onclick="inputNum(this)"></td>
    <td><input type="button" value="9" onclick="inputNum(this)"></td>
    <td><input type="button" value="/" onclick="inputOp(this)"></td>
  </tr>
  <tr>
    <td><input type="button" value="4" onclick="inputNum(this)"></td>
    <td><input type="button" value="5" onclick="inputNum(this)"></td>
    <td><input type="button" value="6" onclick="inputNum(this)"></td>
    <td><input type="button" value="*" onclick="inputOp(this)"></td>
  </tr>
  <tr>
    <td><input type="button" value="1" onclick="inputNum(this)"></td>
    <td><input type="button" value="2" onclick="inputNum(this)"></td>
    <td><input type="button" value="3" onclick="inputNum(this)"></td>
    <td><input type="button" value="-" onclick="inputOp(this)"></td>
  </tr>
  <tr>
    <td><input type="button" value="0" onclick="inputNum(this)"></td>
    <td><input type="button" value="." onclick="inputNum(this)"></td>
    <td><input type="button" value="=" onclick="calcResult(this)"></td>
    <td><input type="button" value="+" onclick="inputOp(this)"></td>
  </tr>
</table>

<script>
const display = document.getElementById('display');
let firstOperand = null;
let operator = null;
let waitingForSecond = false;

function inputNum(btn) {
  if (waitingForSecond) {
    display.value = btn.value;
    waitingForSecond = false;
  } else {
    display.value += btn.value;
  }
}

function inputOp(btn) {
  const inputVal = parseFloat(display.value);
  if (firstOperand === null) {
    firstOperand = inputVal;
  } else if (operator) {
    firstOperand = calculate(firstOperand, inputVal, operator);
    display.value = firstOperand;
  }
  operator = btn.value;
  waitingForSecond = true;
}

function calcResult() {
  if (operator === null || waitingForSecond) return;
  const secondOperand = parseFloat(display.value);
  display.value = calculate(firstOperand, secondOperand, operator);
  firstOperand = null;
  operator = null;
  waitingForSecond = false;
}

function handleFunc(btn) {
  switch (btn.value) {
    case 'C':
      display.value = '';
      firstOperand = null;
      operator = null;
      waitingForSecond = false;
      break;
    case '<--':
      display.value = display.value.slice(0, -1);
      break;
    case 'x²':
      const val = parseFloat(display.value);
      display.value = val * val;
      break;
  }
}

function calculate(a, b, op) {
  switch (op) {
    case '+': return a + b;
    case '-': return a - b;
    case '*': return a * b;
    case '/': return b !== 0 ? a / b : 'Error';
    default: return b;
  }
}
</script>
</body>
</html>

關鍵點解析

  • 輸入框唯讀:readonly 防止鍵盤干擾,僅通過按鈕輸入。
  • 狀態機模式:waitingForSecond 標記是否等待第二操作數,避免連續運算符覆蓋。
  • 錯誤處理:除零返回 'Error',可擴展為異常提示。
  • 擴展性:易於添加百分比、開根號、歷史記錄等功能。

進階優化方向

  1. 使用 eval() 或表達式解析器支持連續混合運算(如 1+2*3)。
  2. 引入鍵盤事件監聽(keydown)實現物理鍵盤操作。
  3. 採用模塊化模式(ES6 Module)分離邏輯與視圖。
  4. 增加單元測試(Jest)保證計算邏輯正確性。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved