网页前端简单计算器代码
时间: 2023-12-11 18:03:41 浏览: 72
以下是一个简单的网页前端计算器代码,可以进行加、减、乘、除四则运算:
```html
<!DOCTYPE html>
<html>
<head>
<title>简单计算器</title>
<meta charset="utf-8">
<style type="text/css">
input[type="button"] {
width: 50px;
height: 30px;
font-size: 16px;
margin: 5px;
}
</style>
</head>
<body>
<input type="text" id="num1" placeholder="请输入第一个数">
<input type="text" id="num2" placeholder="请输入第二个数">
<br>
<input type="button" value="+" onclick="add()">
<input type="button" value="-" onclick="sub()">
<input type="button" value="*" onclick="mul()">
<input type="button" value="/" onclick="div()">
<br>
<input type="text" id="result" placeholder="计算结果">
<script type="text/javascript">
function add() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
document.getElementById("result").value = num1 + num2;
}
function sub() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
document.getElementById("result").value = num1 - num2;
}
function mul() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
document.getElementById("result").value = num1 * num2;
}
function div() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
if (num2 == 0) {
alert("除数不能为0!");
return;
}
document.getElementById("result").value = num1 / num2;
}
</script>
</body>
</html>
```
阅读全文