HTML5在線計算器的代碼如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>在線計算器</title> <style> body { background-color: #f0f0f0; font-family: sans-serif; } h1 { text-align: center; margin-top: 20px; } #calculator { background-color: #fff; border-radius: 10px; margin: 0 auto; padding: 10px; width: 350px; box-shadow: 0 0 10px rgba(0,0,0,0.2); } .input { width: 100%; height: 40px; font-size: 20px; text-align: right; } .button { width: 80px; height: 50px; font-size: 20px; margin: 5px; } </style> </head> <body> <h1>在線計算器</h1> <div id="calculator"> <input class="input" type="text" id="result" readonly> <table> <tr> <td><button class="button" onclick="clearResult()">C</button></td> <td><button class="button" onclick="removeLastChar()"><i class="fa fa-arrow-left"></i></button></td> <td><button class="button" onclick="append('%')">%</button></td> <td><button class="button" onclick="append('/')">/</button></td> </tr> <tr> <td><button class="button" onclick="append('7')">7</button></td> <td><button class="button" onclick="append('8')">8</button></td> <td><button class="button" onclick="append('9')">9</button></td> <td><button class="button" onclick="append('*')">*</button></td> </tr> <tr> <td><button class="button" onclick="append('4')">4</button></td> <td><button class="button" onclick="append('5')">5</button></td> <td><button class="button" onclick="append('6')">6</button></td> <td><button class="button" onclick="append('-')">-</button></td> </tr> <tr> <td><button class="button" onclick="append('1')">1</button></td> <td><button class="button" onclick="append('2')">2</button></td> <td><button class="button" onclick="append('3')">3</button></td> <td><button class="button" onclick="append('+')">+</button></td> </tr> <tr> <td><button class="button" onclick="append('0')">0</button></td> <td><button class="button" onclick="append('.')">.</button></td> <td><button class="button" onclick="calculate()">=</button></td> </tr> </table> </div> <script> function append(value) { document.getElementById("result").value += value; } function clearResult() { document.getElementById("result").value = ""; } function removeLastChar() { var result = document.getElementById("result").value; document.getElementById("result").value = result.substring(0, result.length - 1); } function calculate() { try { var result = eval(document.getElementById("result").value); document.getElementById("result").value = result; } catch (e) { alert("輸入錯誤"); } } </script> </body> </html>以上代碼中包括了HTML、CSS、JavaScript等多種技術,通過HTML定義了頁面結構,CSS定義了頁面樣式,JavaScript編寫了計算器的邏輯。在頁面中使用了table標簽來分隔出不同的按鈕,并使用button標簽來定義按鈕。通過JavaScript中的事件監聽函數,實現了按下按鈕后的對應邏輯操作。其中,eval()函數可以對字符串進行計算并返回計算結果。