要使用 JavaScript 构建一个简单的计算器,我们需要处理基本的算术运算,例如加法、减法、乘法和除法。JavaScript 通常与 HTML 和 CSS 结合使用,以创建交互式的基于 Web 的计算器。
我们将创建什么
我们将构建一个简单且功能齐全的计算器,它将具备以下特点:
- 简洁且响应式的设计。
- 用于每个数字和运算的按钮。
- 显示当前输入和结果的显示区域。
- 用于清除屏幕的按钮。
项目预览
!Screenshot-2025-03-08-152454JavaScript Calculator App
计算器 – HTML 结构与 CSS 样式
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f2f2f2;
margin: 0;
}
.calculator {
width: 300px;
background-color: #fff;
border-radius: 15px;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
padding: 20px;
}
.display {
width: 100%;
height: 50px;
text-align: right;
font-size: 1.5rem;
padding: 10px;
margin-bottom: 20px;
border: none;
background-color: #ffeb3b;
border-radius: 8px;
color: #333;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.button {
background-color: #03a9f4;
border: none;
font-size: 1.5rem;
padding: 20px;
cursor: pointer;
border-radius: 10px;
transition: background-color 0.3s, transform 0.2s;
color: white;
}
.button:hover {
background-color: #0288d1;
transform: scale(1.1);
}
.button:active {
transform: scale(0.95);
}
.button.clear {
background-color: #ff5722;
}
.button.clear:hover {
background-color: #e64a19;
}
.button.equal {
background-color: #8bc34a;
}
.button.equal:hover {
background-color: #689f38;
}
.button.operator {
background-color: #ff9800;
}
.button.operator:hover {
background-color: #f57c00;
}
在此示例中:
- 代码定义了一个简单的计算器界面的 HTML 结构,包含一个用于显示的输入字段以及一组用于数字、运算符和操作的按钮。
- INLINECODE4d572b87 的 INLINECODE8554b3f4 元素充当计算器的显示区域,用户可以在其中查看结果。它被设置为禁用状态,这意味着用户无法直接在其中输入;它仅用于显示输出。
- 计算器的按钮位于