HTML5簡易計算器
以下是計算器實現的代碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>計算器</title> <script> function getResult() { var num1 = parseFloat(document.getElementById('num1').value); var num2 = parseFloat(document.getElementById('num2').value); var operator = document.getElementById('operator').value; if (operator == '+') { document.getElementById('result').innerHTML = num1 + num2; } else if (operator == '-') { document.getElementById('result').innerHTML = num1 - num2; } else if (operator == '*') { document.getElementById('result').innerHTML = num1 * num2; } else { document.getElementById('result').innerHTML = num1 / num2; } } </script> </head> <body> <h1>計算器</h1> <input type="number" id="num1"> <select id="operator"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> <input type="number" id="num2"> <button onclick="getResult()">計算</button> <p>計算結果為:<span id="result"></span></p> </body> </html>
該計算器使用HTML5特性,結合JavaScript代碼實現了加減乘除四則運算。在頁面中的輸入框中輸入兩個數,選擇運算符后點擊計算按鈕,即可得到計算結果。
上一篇html5粗線的代碼