计算器效果图:
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>计算器</title>
</head>
<body>
<script>
var a = "x"; /*运算符前数字*/
var aa = 0; /*运算符前数字已经输入的位数*/
var b = "x"; /*运算符后数字*/
var bb = 0; /*运算符后数字已经输入的位数*/
var c = 0; /*运算符 0表示无,1为+,2为-,3为*,4为/ */
//带参函数,获取运算符前后数字
function num(numget) {
var textUse1 = document.getElementById("text1"); /*获取文本框对象*/
var textUse3 = document.getElementById("text3"); /*获取文本框对象*/
if(c == 0) {
if(aa == 0) {
a = numget;
aa++;
textUse1.value = a; /*设置文本框1的值*/
} else {
if(aa != 0) {
a = a * 10 + numget;
aa++;
textUse1.value = a; /*设置文本框1的值*/
}
}
} else {
if(bb == 0) {
b = numget;
bb++;
textUse3.value = b; /*设置文本框3的值*/
} else {
if(bb != 0) {
b = b * 10 + numget;
bb++;
textUse3.value = b; /*设置文本框3的值*/
}
}
}
}
//获取运算符
function numsym(symget) {
var textUse2 = document.getElementById("text2"); /*获取文本框对象*/
c = symget;
if(c == 1) {
textUse2.value = "+"; /*根据输入的运算符,设置文本框2的值*/
}
if(c == 2) {
textUse2.value = "-";
}
if(c == 3) {
textUse2.value = "*";
}
if(c == 4) {
textUse2.value = "÷";
}
}
//根据运算符执行不同运算
function numout() {
var textUse = document.getElementById("textId"); /*获取文本框对象*/
if(c == 1) {
alert(a + b);
}
if(c == 2) {
alert(a - b);
}
if(c == 3) {
alert(a * b);
}
if(c == 4) {
alert(a / b);
}
location.reload() /*运算结束自动刷新页面*/
}
//按钮
</script>
<style>
button {
width: 100px;
height: 60px;
border-color: blue;
background-color: black;
color: yellow;
font-size: 30px;
}
input {
width: 103px;
height: 60px;
border: 0px;
background-color: white;
color: black;
font-size: 30px;
}
</style>
<div>
<input id="text1" type="text" readonly="readonly" autocomplete="off">
<input id="text2" type="text" readonly="readonly" autocomplete="off">
<input id="text3" type="text" readonly="readonly" autocomplete="off">
</div>
<div>
<button type="button" onclick="num(1)">1</button>
<button type="button" onclick="num(2)">2</button>
<button type="button" onclick="num(3)">3</button>
<button type="button" onclick="numsym(1)">+</button><br>
<button type="button" onclick="num(4)">4</button>
<button type="button" onclick="num(5)">5</button>
<button type="button" onclick="num(6)">6</button>
<button type="button" onclick="numsym(2)">-</button><br>
<button type="button" onclick="num(7)">7</button>
<button type="button" onclick="num(8)">8</button>
<button type="button" onclick="num(9)">9</button>
<button type="button" onclick="numsym(3)">*</button><br>
<button type="button">.</button>
<button type="button" onclick="num(0)">0</button>
<button type="button" onclick="numout()">=</button>
<button type="button" onclick="numsym(4)">/</button><br><br>
<strong>可以对两个任意长度的数字进行加减乘除基本运算,<br>运算结果弹窗显示,运算结束后页面自动刷新。</strong>
</div>
</body>
</html>