基于JavaScript实现简易计算器

本文实例为大家分享了JavaScript实现简易计算器的具体代码,供大家参考,具体内容如下

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>计算器</title>

<style>

.op {

margin: 50px auto;

width: 300px;

height: 300px;

border: 1px solid orange;

background-color: lightskyblue;

border-radius: 50px;

}

input {

width: 210px;

height: 30px;

border-radius: 5px;

}

button {

width: 30px;

height: 30px;

border-radius: 10px;

}

</style>

</head>

<body>

<div class="op">

<h2 align="center">计算器</h2>

<form name="calculator">

<table align="center">

<tr>

<td>num1:</td>

<td><input type="text" name="num1"></td>

</tr>

<tr>

<td>num2:</td>

<td><input type="text" name="num2"></td>

</tr>

<tr>

<td colspan="2">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp

<button type="button">+</button>

&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp

<button type="button">-</button>

&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp

<button type="button">*</button>

&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp

<button type="button">/</button>

</td>

</tr>

<tr>

<td>结果:</td>

<td><input type="text" name="result" disabled></td>

</tr>

</table>

</form>

</div>

<script>

//得到标签名下的所有元素对象,返回一个数组

let buttonArr = document.getElementsByTagName("button");

for (let but of buttonArr) {

but.addEventListener('click', function () {

let operator = this.innerHTML;

count(operator);

});

}

function count(operator) {

//得到form为calculator中name为num1的输入值

let num1 = parseFloat(document.calculator.num1.value);

let num2 = parseFloat(document.calculator.num2.value);

let result = '';

switch (operator) {

case '+':

result = num1 + num2;

break;

case '-':

result = num1 - num2;

break;

case '*':

result = num1 * num2;

break;

case '/':

if (num2 == 0) {

alert("除数不能为零");

return;

}

result = num1 / num2;

break;

}

//将结果赋值于属性名name为result的input框

document.calculator.result.value = result;

}

</script>

</body>

</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

以上是 基于JavaScript实现简易计算器 的全部内容, 来源链接: utcz.com/p/220816.html

回到顶部