数字输入计算器
时间: 2023-08-12 13:07:47 浏览: 56
以下是一个简单的数字输入计算器的 HTML、CSS 和 JavaScript 代码示例,支持加、减、乘、除四种基本运算:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>数字输入计算器</title>
<style>
.calculator {
width: 300px;
margin: 50px auto;
border: 1px solid #ccc;
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 10px #ccc;
}
.calculator input[type="number"] {
width: 100%;
margin-bottom: 10px;
box-sizing: border-box;
padding: 5px;
border: 1px solid #ccc;
border-radius: 3px;
}
.calculator button {
width: 25%;
margin-right: 5px;
margin-bottom: 5px;
box-sizing: border-box;
padding: 5px;
border: 1px solid #ccc;
border-radius: 3px;
background-color: #f2f2f2;
cursor: pointer;
}
.calculator button:last-child {
margin-right: 0;
}
.calculator button:hover {
background-color: #e6e6e6;
}
</style>
</head>
<body>
<div class="calculator">
<input type="number" id="num1" placeholder="请输入第一个数字">
<input type="number" id="num2" placeholder="请输入第二个数字">
<div>
<button onclick="calculate('+')">+</button>
<button onclick="calculate('-')">-</button>
<button onclick="calculate('*')">*</button>
<button onclick="calculate('/')">/</button>
</div>
<p>计算结果:<span id="result"></span></p>
</div>
<script>
function calculate(operator) {
var num1 = Number(document.getElementById("num1").value);
var num2 = Number(document.getElementById("num2").value);
var result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
result = '未知运算符';
}
document.getElementById("result").innerHTML = result;
}
</script>
</body>
</html>
```
这个计算器使用了 HTML5 的 `input` 标签中的 `type="number"` 属性来限制输入为数字类型,同时使用了 JavaScript 的 `switch` 语句来根据不同的运算符进行计算,并将结果通过 `innerHTML` 属性显示在页面上。CSS 样式部分使用了一些简单的布局和样式设计来美化计算器界面。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)