用html、css、js做一个简单的计算器
以下是一个简单的网页计算器示例,使用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>Simple Calculator</title>
<style>
.calculator {
margin: auto;
text-align: center;
width: 200px;
padding: 10px;
border: 1px solid #ccc;
}
input[type="text"] {
width: 90%;
margin-bottom: 10px;
padding: 5px;
}
input[type="button"] {
width: 40px;
margin: 5px;
}
</style>
</head>
<body>
<div class="calculator">
<input type="text" id="display" disabled>
<br>
<input type="button" value="1" onclick="press('1')">
<input type="button" value="2" onclick="press('2')">
<input type="button" value="3" onclick="press('3')">
<input type="button" value="+" onclick="press('+')">
<br>
<input type="button" value="4" onclick="press('4')">
<input type="button" value="5" onclick="press('5')">
<input type="button" value="6" onclick="press('6')">
<input type="button" value="-" onclick="press('-')">
<br>
<input type="button" value="7" onclick="press('7')">
<input type="button" value="8" onclick="press('8')">
<input type="button" value="9" onclick="press('9')">
<input type="button" value="*" onclick="press('*')">
<br>
<input type="button" value="0" onclick="press('0')">
<input type="button" value="Clear" onclick="clearDisplay()">
<input type="button" value="=" onclick="calculate()">
<input type="button" value="/" onclick="press('/')">
</div>
<script>
let current = 0;
let operator = "";
const display = document.getElementById("display");
function press(btn) {
if (btn === "Clear") {
clearDisplay();
} else {
display.value = display.value + btn;
}
}
function clearDisplay() {
display.value = "";
}
function calculate() {
const input = display.value;
if (input) {
const result = eval(input);
display.value = result;
}
}
</script>
</body>
</html>
这个计算器有基本的数字键、运算符键和清除键。输入数字后,选择运算符并输入另一个数字,最后按下等号键计算结果。使用eval
函数来执行表达式计算。这个示例简单易懂,但不包括错误处理和额外功能,如处理多位数字和小数。
评论已关闭