前端案例:简易计算器(html+css+JavaScript)
以下是一个简易的计算器实现示例,使用HTML、CSS和JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简易计算器</title>
<style>
.calculator {
margin: auto;
text-align: center;
width: 200px;
padding: 10px;
border: 1px solid #ccc;
}
input[type="text"] {
width: 90%;
margin-bottom: 10px;
}
button {
width: 40px;
margin: 5px;
}
</style>
</head>
<body>
<div class="calculator">
<input type="text" id="display" disabled>
<button onclick="operate('1')">1</button>
<button onclick="operate('2')">2</button>
<button onclick="operate('3')">3</button>
<button onclick="operate('+')">+</button><br>
<button onclick="operate('4')">4</button>
<button onclick="operate('5')">5</button>
<button onclick="operate('6')">6</button>
<button onclick="operate('-')">-</button><br>
<button onclick="operate('7')">7</button>
<button onclick="operate('8')">8</button>
<button onclick="operate('9')">9</button>
<button onclick="operate('*')">×</button><br>
<button onclick="operate('0')">0</button>
<button onclick="operate('.')">.</button>
<button onclick="operate('clear')">C</button>
<button onclick="operate('equals')">=</button>
<button onclick="operate('/')">÷</button>
</div>
<script>
// 初始显示屏幕
let display = document.getElementById('display');
let operator = null;
let firstNum = null;
function operate(val) {
if (isOperator(val)) {
operator = val;
// 获取显示屏幕的值
firstNum = parseFloat(display.value);
// 清空显示屏幕以准备接收第二个数
display.value = '';
} else if (val === 'clear') {
// 清除所有操作数和运算符
firstNum = null;
operator = null;
display.value = '';
} else if (val === 'equals') {
// 计算结果
let secondNum = parseFloat(display.value);
let result = performOperation(firstNum, secondNum, operator);
display.value = result.toString();
// 清除运算符
operator = null;
} else {
// 添加数字到显示屏幕
if (display.value === '0' || display.value === '') {
display.value = ''; // 清除开头的0
}
display.value += val;
}
}
function isOperator(val) {
return ['+', '-', '*', '/', '='].includes(val);
}
function performOperatio
评论已关闭