模擬計算器的html
from https://chat.openai.com/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0; /* 避免body的默認margin影響 */
height: 100vh; /* 將body擴展到整個視窗高度 */
display: flex;
align-items: center;
justify-content: center;
}
#calculator {
width: 300px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input {
width: 100%;
margin-bottom: 10px;
padding: 10px;
box-sizing: border-box;
font-size: 18px;
}
button {
width: 48px;
height: 48px;
margin: 5px;
font-size: 18px;
}
</style>
</head>
<body>
<div id="calculator">
<input type="text" id="display" disabled>
<br>
<button onclick="appendToDisplay('7')">7</button>
<button onclick="appendToDisplay('8')">8</button>
<button onclick="appendToDisplay('9')">9</button>
<button onclick="setOperator('/')">/</button>
<br>
<button onclick="appendToDisplay('4')">4</button>
<button onclick="appendToDisplay('5')">5</button>
<button onclick="appendToDisplay('6')">6</button>
<button onclick="setOperator('*')">*</button>
<br>
<button onclick="appendToDisplay('1')">1</button>
<button onclick="appendToDisplay('2')">2</button>
<button onclick="appendToDisplay('3')">3</button>
<button onclick="setOperator('-')">-</button>
<br>
<button onclick="appendToDisplay('0')">0</button>
<button onclick="clearDisplay()">C</button>
<button onclick="calculate()">=</button>
<button onclick="setOperator('+')">+</button>
</div>
<script>
// 取得顯示區域
var display = document.getElementById("display");
// 儲存計算的數字和運算符號
var firstNumber = "";
var operator = "";
// 在顯示區域追加數字
function appendToDisplay(value) {
display.value += value;
}
// 設定運算符號
function setOperator(op) {
if (operator !== "") {
calculate();
}
operator = op;
firstNumber = display.value;
display.value = "";
}
// 清空顯示區域
function clearDisplay() {
display.value = "";
firstNumber = "";
operator = "";
}
// 進行計算
function calculate() {
var secondNumber = display.value;
var result = 0;
switch (operator) {
case '+':
result = parseFloat(firstNumber) + parseFloat(secondNumber);
break;
case '-':
result = parseFloat(firstNumber) - parseFloat(secondNumber);
break;
case '*':
result = parseFloat(firstNumber) * parseFloat(secondNumber);
break;
case '/':
result = parseFloat(firstNumber) / parseFloat(secondNumber);
break;
}
// 顯示計算結果
display.value = result;
// 重置運算符號和數字
operator = "";
firstNumber = "";
}
</script>
</body>
</html>
留言
張貼留言