HTML小項目代碼示例
<!DOCTYPE html> <html> <head> <title>計算器</title> <meta charset="utf-8"> <style> /* 樣式表 */ </style> </head> <body> <h1>計算器</h1> <form> <input type="text" id="input1"> <select id="select1"> <option value="add">+</option> <option value="subtract">-</option> <option value="multiply">*</option> <option value="divide">/</option> </select> <input type="text" id="input2"> <input type="button" value="計算" onclick="calculate()"> </form> <script> function calculate() { var num1 = parseFloat(document.getElementById("input1").value); var num2 = parseFloat(document.getElementById("input2").value); var operator = document.getElementById("select1").value; var result; switch (operator) { case "add": result = num1 + num2; break; case "subtract": result = num1 - num2; break; case "multiply": result = num1 * num2; break; case "divide": if (num2 === 0) { alert("除數不能為0"); return; } else { result = num1 / num2; break; } } document.write(num1 + " " + operator + " " + num2 + " = " + result); } </script> </body> </html>
本文演示了一個簡單的計算器項目。代碼包括HTML表單和JavaScript函數,用戶可以在下拉菜單中選擇加、減、乘、除四種運算中的一種,并輸入兩個數字進行計算。如果用戶輸入的是0,則會出現“除數不能為0”的警告。最后,頁面會顯示計算結果。