萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 網頁版計算機:從零打造互動式四則運算工具

功能特色

  • 支援加、減、乘、除四則運算。
  • 支援小數點與連續運算。
  • 「=」鍵顯示完整算式與結果(如 1+2=3)。
  • 運算後自動進入「清除旗標」模式,下一次輸入數字會重置螢幕。

完整原始碼

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>簡易計算機</title>
    <style>
        body { font-family: sans-serif; display: flex; justify-content: center; margin-top: 3rem; }
        table { border-collapse: collapse; }
        td { padding: 0; }
        input[type=text] { width: 100%; height: 40px; font-size: 1.5rem; text-align: right; padding: 0 0.5rem; box-sizing: border-box; border: 1px solid #ccc; }
        input[type=button] { width: 60px; height: 50px; font-size: 1.2rem; cursor: pointer; border: 1px solid #bbb; background: #f9f9f9; }
        input[type=button]:active { background: #e0e0e0; }
        .operator { background: #ffe0b2; }
        .equal { background: #c8e6c9; }
    </style>
</head>
<body>
    <table>
        <tr>
            <td colspan="4"><input type="text" id="display" readonly></td>
        </tr>
        <tr>
            <td><input type="button" value="1" onclick="appendNum('1')"></td>
            <td><input type="button" value="2" onclick="appendNum('2')"></td>
            <td><input type="button" value="3" onclick="appendNum('3')"></td>
            <td><input type="button" class="operator" value="+" onclick="appendNum('+')"></td>
        </tr>
        <tr>
            <td><input type="button" value="4" onclick="appendNum('4')"></td>
            <td><input type="button" value="5" onclick="appendNum('5')"></td>
            <td><input type="button" value="6" onclick="appendNum('6')"></td>
            <td><input type="button" class="operator" value="-" onclick="appendNum('-')"></td>
        </tr>
        <tr>
            <td><input type="button" value="7" onclick="appendNum('7')"></td>
            <td><input type="button" value="8" onclick="appendNum('8')"></td>
            <td><input type="button" value="9" onclick="appendNum('9')"></td>
            <td><input type="button" class="operator" value="×" onclick="appendNum('*')"></td>
        </tr>
        <tr>
            <td><input type="button" value="0" onclick="appendNum('0')"></td>
            <td><input type="button" value="." onclick="appendNum('.')"></td>
            <td><input type="button" class="equal" value="=" onclick="calculate()"></td>
            <td><input type="button" class="operator" value="÷" onclick="appendNum('/')"></td>
        </tr>
    </table>

    <script>
        const display = document.getElementById('display');
        let clearFlag = false; // 運算完成後,下一個輸入應清空螢幕

        function appendNum(val) {
            if (clearFlag) {
                display.value = '';
                clearFlag = false;
            }
            // 避免連續運算符
            const lastChar = display.value.slice(-1);
            if ('+-*/'.includes(val) && '+-*/'.includes(lastChar)) {
                display.value = display.value.slice(0, -1) + val;
                return;
            }
            display.value += val;
        }

        function calculate() {
            try {
                // 安全評估:僅允許數字、運算符、小數點
                if (!/^[\d+\-*/.()]+$/.test(display.value)) throw new Error('非法字元');
                const result = eval(display.value);
                if (!isFinite(result)) throw new Error('除以零或溢位');
                display.value += '=' + result;
            } catch (e) {
                display.value = '錯誤';
            }
            clearFlag = true;
        }
    </script>
</body>
</html>

核心邏輯說明

  1. 顯示區域: 唯一的 <input type="text" id="display"> 同時作為輸入與結果顯示,設為 readonly 避免鍵盤干擾。
  2. 清除旗標 clearFlag: 運算完成後設為 true,下一次點擊數字鍵時先清空螢幕,模擬實體計算機行為。
  3. 運算符連續輸入處理: 若使用者連點兩次運算符,自動替換為最新運算符,而非疊加。
  4. 使用 eval() 計算: 為教學示範簡化邏輯;實務專案建議自行實作解析器或使用 math.js 等庫以避免安全風險。
  5. 錯誤處理: 捕捉除以零、語法錯誤等異常,顯示「錯誤」並重置旗標。

樣式亮點

  • 運算符鍵(橘色系)與等號鍵(綠色系)視覺區隔。
  • 按鈕按下時的 :active 回饋增強手感。
  • 響應式寬度,適應行動裝置。

擴充方向

  • 加入清除 (C)、倒退鍵 (⌫)、正負號 (+/-)、百分比 (%) 功能鍵。
  • 支援鍵盤輸入(數字鍵、Enter、Escape、Backspace)。
  • 歷史紀錄面板,記錄過往運算式。
  • 科學計算模式(三角函數、對數、次方等)。

這個計算機範例展示了如何用極簡的 HTML/CSS/JS 打造一個功能完整、互動流暢的網頁小工具,是前端入門的經典練習專案。

copyright © 萬盛學電腦網 all rights reserved