您好,登录后才能下订单哦!
在现代Web开发中,JavaScript已经成为前端开发的核心技术之一。通过JavaScript,我们可以实现各种复杂的交互功能,甚至可以在浏览器中模拟桌面应用程序的功能。本文将详细介绍如何使用JavaScript来仿制Windows计算器的功能。我们将从项目结构、HTML、CSS到JavaScript逻辑一步步进行讲解,最终实现一个功能完整的计算器。
在开始编写代码之前,我们需要先规划一下项目的结构。一个简单的计算器项目通常包括以下几个部分:
我们将分别创建这三个文件,并在HTML文件中引入CSS和JavaScript文件。
首先,我们需要创建一个HTML文件来定义计算器的界面结构。计算器的界面通常包括一个显示屏和一系列按钮。我们可以使用HTML的<div>
元素来创建这些组件。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript计算器</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<div class="display" id="display">0</div>
<div class="buttons">
<button class="btn clear" id="clear">C</button>
<button class="btn backspace" id="backspace">←</button>
<button class="btn operator" id="divide">÷</button>
<button class="btn operator" id="multiply">×</button>
<button class="btn number" id="seven">7</button>
<button class="btn number" id="eight">8</button>
<button class="btn number" id="nine">9</button>
<button class="btn operator" id="subtract">-</button>
<button class="btn number" id="four">4</button>
<button class="btn number" id="five">5</button>
<button class="btn number" id="six">6</button>
<button class="btn operator" id="add">+</button>
<button class="btn number" id="one">1</button>
<button class="btn number" id="two">2</button>
<button class="btn number" id="three">3</button>
<button class="btn equals" id="equals">=</button>
<button class="btn number zero" id="zero">0</button>
<button class="btn decimal" id="decimal">.</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
在这个HTML结构中,我们创建了一个<div>
元素作为计算器的容器,并在其中定义了一个显示屏和一系列按钮。每个按钮都有一个唯一的id
,以便在JavaScript中引用。
接下来,我们需要为计算器添加一些样式,使其看起来更像Windows计算器。我们可以使用CSS来设置计算器的布局、颜色、字体等。
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
.calculator {
width: 300px;
background-color: #333;
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
overflow: hidden;
}
.display {
background-color: #222;
color: #fff;
font-size: 2.5em;
text-align: right;
padding: 20px;
box-sizing: border-box;
height: 80px;
display: flex;
align-items: center;
justify-content: flex-end;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1px;
}
.btn {
background-color: #444;
color: #fff;
border: none;
font-size: 1.5em;
padding: 20px;
cursor: pointer;
transition: background-color 0.2s;
}
.btn:hover {
background-color: #555;
}
.btn:active {
background-color: #666;
}
.btn.operator {
background-color: #ff9500;
}
.btn.operator:hover {
background-color: #ffaa33;
}
.btn.operator:active {
background-color: #cc7700;
}
.btn.equals {
background-color: #ff2d55;
grid-column: span 2;
}
.btn.equals:hover {
background-color: #ff4d6a;
}
.btn.equals:active {
background-color: #cc2244;
}
.btn.clear {
background-color: #ff3b30;
}
.btn.clear:hover {
background-color: #ff5c52;
}
.btn.clear:active {
background-color: #cc3026;
}
.btn.backspace {
background-color: #ff9500;
}
.btn.backspace:hover {
background-color: #ffaa33;
}
.btn.backspace:active {
background-color: #cc7700;
}
.btn.zero {
grid-column: span 2;
}
在这个CSS文件中,我们为计算器的各个部分设置了样式。我们使用了grid
布局来排列按钮,并为不同类型的按钮设置了不同的背景颜色和悬停效果。
现在,我们已经完成了计算器的界面设计和样式设置,接下来我们将使用JavaScript来实现计算器的逻辑功能。
首先,我们需要定义一些变量来存储计算器的状态。这些变量包括当前显示的值、上一个操作数、当前运算符等。
let displayValue = '0';
let firstOperand = null;
let secondOperand = null;
let currentOperator = null;
let shouldResetDisplay = false;
displayValue
:当前显示在计算器屏幕上的值。firstOperand
:第一个操作数。secondOperand
:第二个操作数。currentOperator
:当前选择的运算符。shouldResetDisplay
:一个布尔值,用于指示是否应该在输入下一个数字时重置显示屏。接下来,我们需要为计算器的按钮添加事件监听器,以便在用户点击按钮时执行相应的操作。
const display = document.getElementById('display');
const numberButtons = document.querySelectorAll('.number');
const operatorButtons = document.querySelectorAll('.operator');
const clearButton = document.getElementById('clear');
const backspaceButton = document.getElementById('backspace');
const decimalButton = document.getElementById('decimal');
const equalsButton = document.getElementById('equals');
numberButtons.forEach(button => {
button.addEventListener('click', () => {
appendNumber(button.textContent);
});
});
operatorButtons.forEach(button => {
button.addEventListener('click', () => {
chooseOperator(button.textContent);
});
});
clearButton.addEventListener('click', clear);
backspaceButton.addEventListener('click', backspace);
decimalButton.addEventListener('click', appendDecimal);
equalsButton.addEventListener('click', calculate);
在这个代码片段中,我们为数字按钮、运算符按钮、清除按钮、退格按钮、小数点按钮和等号按钮分别添加了事件监听器。每个按钮被点击时,都会调用相应的函数来处理输入。
当用户点击数字按钮时,我们需要将数字添加到显示屏上。如果显示屏上的值是0
,或者需要重置显示屏,我们将直接替换显示屏上的值。
function appendNumber(number) {
if (displayValue === '0' || shouldResetDisplay) {
displayValue = number;
shouldResetDisplay = false;
} else {
displayValue += number;
}
updateDisplay();
}
appendNumber
函数接收一个数字作为参数,并将其添加到displayValue
中。displayValue
是0
,或者shouldResetDisplay
为true
,我们将直接替换displayValue
。updateDisplay
函数来更新显示屏上的值。当用户点击运算符按钮时,我们需要保存当前的操作数和运算符,并准备接收下一个操作数。
function chooseOperator(operator) {
if (currentOperator !== null) {
calculate();
}
firstOperand = displayValue;
currentOperator = operator;
shouldResetDisplay = true;
}
chooseOperator
函数接收一个运算符作为参数。currentOperator
不为null
,说明之前已经选择了一个运算符,我们需要先执行计算。firstOperand
,并更新currentOperator
。shouldResetDisplay
设置为true
,以便在输入下一个数字时重置显示屏。当用户点击等号按钮时,我们需要执行计算并显示结果。
function calculate() {
if (currentOperator === null || shouldResetDisplay) {
return;
}
secondOperand = displayValue;
displayValue = operate(firstOperand, secondOperand, currentOperator);
updateDisplay();
currentOperator = null;
}
calculate
函数首先检查currentOperator
是否为null
,或者是否需要重置显示屏。如果是,则直接返回。secondOperand
,并调用operate
函数执行计算。currentOperator
重置为null
。当用户点击清除按钮时,我们需要重置计算器的所有状态。
function clear() {
displayValue = '0';
firstOperand = null;
secondOperand = null;
currentOperator = null;
shouldResetDisplay = false;
updateDisplay();
}
clear
函数将所有变量重置为初始状态,并更新显示屏。当用户点击小数点按钮时,我们需要将小数点添加到当前显示的值中。如果当前值已经包含小数点,则不进行任何操作。
function appendDecimal() {
if (shouldResetDisplay) {
displayValue = '0.';
shouldResetDisplay = false;
} else if (!displayValue.includes('.')) {
displayValue += '.';
}
updateDisplay();
}
appendDecimal
函数首先检查是否需要重置显示屏。如果是,则将displayValue
设置为'0.'
。displayValue
中。updateDisplay
函数来更新显示屏。当用户点击退格按钮时,我们需要删除当前显示值的最后一个字符。如果删除后显示值为空,则将其设置为0
。
function backspace() {
if (displayValue.length === 1) {
displayValue = '0';
} else {
displayValue = displayValue.slice(0, -1);
}
updateDisplay();
}
backspace
函数首先检查displayValue
的长度。如果长度为1,则将其设置为'0'
。slice
方法删除最后一个字符,并更新displayValue
。updateDisplay
函数来更新显示屏。为了方便起见,我们定义一个updateDisplay
函数来更新显示屏上的值。
function updateDisplay() {
display.textContent = displayValue;
}
updateDisplay
函数将displayValue
的值设置为显示屏的文本内容。最后,我们需要定义一个operate
函数来执行实际的数学运算。
function operate(a, b, operator) {
a = parseFloat(a);
b = parseFloat(b);
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '×':
return a * b;
case '÷':
return a / b;
default:
return b;
}
}
operate
函数接收两个操作数和一个运算符作为参数,并根据运算符执行相应的数学运算。parseFloat
将字符串转换为浮点数,然后使用switch
语句根据运算符执行相应的操作。以下是完整的HTML、CSS和JavaScript代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript计算器</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<div class="display" id="display">0</div>
<div class="buttons">
<button class="btn clear" id="clear">C</button>
<button class="btn backspace" id="backspace">←</button>
<button class="btn operator" id="divide">÷</button>
<button class="btn operator" id="multiply">×</button>
<button class="btn number" id="seven">7</button>
<button class="btn number" id="eight">8</button>
<button class="btn number" id="nine">9</button>
<button class="btn operator" id="subtract">-</button>
<button class="btn number" id="four">4</button>
<button class="btn number" id="five">5</button>
<button class="btn number" id="six">6</button>
<button class="btn operator" id="add">+</button>
<button class="btn number" id="one">1</button>
<button class="btn number" id="two">2</button>
<button class="btn number" id="three">3</button>
<button class="btn equals" id="equals">=</button>
<button class="btn number zero" id="zero">0</button>
<button class="btn decimal" id="decimal">.</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
.calculator {
width: 300px;
background-color: #333;
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
overflow: hidden;
}
.display {
background-color: #222;
color: #fff;
font-size: 2.5em;
text-align: right;
padding: 20px;
box-sizing: border-box;
height: 80px;
display: flex;
align-items: center;
justify-content: flex-end;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1px;
}
.btn {
background-color: #444;
color: #fff;
border: none;
font-size: 1.5em;
padding: 20px;
cursor: pointer;
transition: background-color 0.2s;
}
.btn:hover {
background-color: #555;
}
.btn:active {
background-color: #666;
}
.btn.operator {
background-color: #ff9500;
}
.btn.operator:hover {
background-color: #ffaa33;
}
.btn.operator:active {
background-color: #cc7700;
}
.btn.equals {
background-color: #ff2d55;
grid-column: span 2;
}
.btn.equals:hover {
background-color: #ff4d6a;
}
.btn.equals:active {
background-color: #cc2244;
}
.btn.clear {
background-color: #ff3b30;
}
.btn.clear:hover {
background-color: #ff5c52;
}
.btn.clear:active {
background-color: #cc3026;
}
.btn.backspace {
background-color: #ff9500;
}
.btn.backspace:hover {
background-color: #ffaa33;
}
.btn.backspace:active {
background-color: #cc7700;
}
.btn.zero {
grid-column: span 2;
}
”`javascript let displayValue = ‘0’; let firstOperand = null; let secondOperand = null; let currentOperator = null; let shouldResetDisplay = false;
const display = document.getElementById(‘display’); const numberButtons = document.querySelectorAll(‘.number’); const operatorButtons = document.querySelectorAll(‘.operator’); const clearButton = document.getElementById(‘clear’); const backspaceButton = document.getElementById(‘backspace’); const decimalButton = document.getElementById(‘decimal’); const equalsButton = document.getElementById(‘equals’);
numberButtons.forEach(button => { button.addEventListener(‘click’, () => { appendNumber(button.textContent); }); });
operatorButtons.forEach(button => { button.addEventListener(‘click’, () => { chooseOperator(button.textContent); }); });
clearButton.addEventListener(‘click’, clear); backspaceButton.addEventListener(‘click’, backspace); decimalButton.addEventListener(‘click’, appendDecimal); equalsButton.addEventListener(‘click’, calculate);
function appendNumber(number) { if (displayValue === ‘0’ || shouldResetDisplay) { displayValue = number; shouldResetDisplay = false; } else { displayValue += number; } updateDisplay(); }
function chooseOperator(operator) { if (currentOperator !== null) { calculate(); } firstOperand = displayValue; currentOperator = operator; shouldResetDisplay = true
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。