HTML5是一種用于創建Web內容的最新版本的超文本標記語言。在這個新版本中,新增了更多的標簽和屬性,以提供更多的功能和更高的效率。其中,計算器是常見的一個應用。下面我們將介紹一組使用HTML5編寫的網頁計算器代碼。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HTML5計算器</title> </head> <body> <h1>HTML5計算器</h1> <form> <input type="text" id="result" readonly> <br> <input type="button" value="AC" onclick="clearResult()"> <input type="button" value="±" onclick="changeSign()"> <input type="button" value="%" onclick="percent()"> <input type="button" value="/" onclick="operate(this)"> <br> <input type="button" value="7" onclick="inputNum(this)"> <input type="button" value="8" onclick="inputNum(this)"> <input type="button" value="9" onclick="inputNum(this)"> <input type="button" value="*" onclick="operate(this)"> <br> <input type="button" value="4" onclick="inputNum(this)"> <input type="button" value="5" onclick="inputNum(this)"> <input type="button" value="6" onclick="inputNum(this)"> <input type="button" value="-" onclick="operate(this)"> <br> <input type="button" value="1" onclick="inputNum(this)"> <input type="button" value="2" onclick="inputNum(this)"> <input type="button" value="3" onclick="inputNum(this)"> <input type="button" value="+" onclick="operate(this)"> <br> <input type="button" value="0" onclick="inputNum(this)"> <input type="button" value="." onclick="inputDot(this)"> <input type="button" value="=" onclick="result()"> </form> <script> var num1 = "", num2 = "", operator = ""; function inputNum(btn) { if (operator == "") { num1 += btn.value; document.getElementById("result").value = num1; } else { num2 += btn.value; document.getElementById("result").value = num2; } } function inputDot(btn) { if (operator == "") { if (num1.indexOf(".") == -1) { num1 += btn.value; document.getElementById("result").value = num1; } } else { if (num2.indexOf(".") == -1) { num2 += btn.value; document.getElementById("result").value = num2; } } } function operate(btn) { operator = btn.value; } function result() { var result = 0; if (operator == "+") { result = parseFloat(num1) + parseFloat(num2); } else if (operator == "-") { result = parseFloat(num1) - parseFloat(num2); } else if (operator == "*") { result = parseFloat(num1) * parseFloat(num2); } else if (operator == "/") { result = parseFloat(num1) / parseFloat(num2); } document.getElementById("result").value = result; num1 = result.toString(); num2 = ""; operator = ""; } function clearResult() { num1 = ""; num2 = ""; operator = ""; document.getElementById("result").value = ""; } function changeSign() { var result = parseFloat(document.getElementById("result").value); result = -result; document.getElementById("result").value = result; } function percent() { var result = parseFloat(document.getElementById("result").value); result = result / 100; document.getElementById("result").value = result; } </script> </body> </html>
上面的代碼使用了HTML5的功能創建了一個簡單的計算器。使用了form表單和input標簽,其中readonly屬性是讓文本框處于只讀狀態。JS部分通過監聽按鈕的點擊事件,實現了輸入數字,輸入小數點,選擇運算符,計算結果等功能。
下一篇js里面css樣式