123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- .calculator {
- max-width: 300px;
- margin: 0 auto;
- border: 1px solid #ccc;
- padding: 10px;
- }
- .output {
- background-color: #f1f1f1;
- text-align: right;
- padding: 10px;
- margin-bottom: 10px;
- }
- .buttons {
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: 10px;
- }
- button {
- padding: 10px;
- font-size: 16px;
- background-color: #3498db;
- color: #fff;
- border: none;
- cursor: pointer;
- transition: background-color 0.3s ease;
- }
- button:hover {
- background-color: #2980b9;
- }
- </style>
- </head>
- <body>
- <div class="calculator">
- <div class="output" id="output">0</div>
- <div class="buttons">
- <button onclick="appendNumber('7')">7</button>
- <button onclick="appendNumber('8')">8</button>
- <button onclick="appendNumber('9')">9</button>
- <button onclick="appendOperator('+')">+</button>
- <button onclick="appendNumber('4')">4</button>
- <button onclick="appendNumber('5')">5</button>
- <button onclick="appendNumber('6')">6</button>
- <button onclick="appendOperator('-')">-</button>
- <button onclick="appendNumber('1')">1</button>
- <button onclick="appendNumber('2')">2</button>
- <button onclick="appendNumber('3')">3</button>
- <button onclick="appendOperator('*')">*</button>
- <button onclick="appendNumber('0')">0</button>
- <button onclick="appendNumber('.')">.</button>
- <button onclick="calculate()">=</button>
- <button onclick="appendOperator('/')">/</button>
- <button onclick="clearExpression()">C</button>
- <button onclick="backspace()">⌫</button>
- </div>
- </div>
- <script>
- let outputDiv = document.getElementById('output');
- let expression = '';
- function appendNumber(number) {
- expression += number;
- outputDiv.innerText = expression;
- }
- function appendOperator(operator) {
- if (expression.slice(-1) === '+' || expression.slice(-1) === '-' || expression.slice(-1) === '*' || expression.slice(-1) === '/') {
- expression = expression.slice(0, -1);
- }
- expression += operator;
- outputDiv.innerText = expression;
- }
- function calculate() {
- try {
- const result = eval(expression);
- expression = result.toString();
- outputDiv.innerText = expression;
- } catch (error) {
- // 处理错误
- expression = '';
- outputDiv.innerText = 'Error';
- }
- }
- function clearExpression() {
- expression = '';
- outputDiv.innerText = '0';
- }
- function backspace() {
- if (expression === '' || expression === '0') {
- return;
- }
- if (expression.length === 1) {
- expression = '0';
- } else {
- expression = expression.slice(0, -1);
- }
- outputDiv.innerText = expression;
- }
- </script>
- </body>
- </html>
|