用JavaScript编写一个计算器
开发工具与关键技术:JavaScript
作者:陈希雄
撰写时间:2019/1/25
源码:
<body>
<div style="width: 491px; height: 343px;background-color:#514e4a;margin-left:20%" >
<div style="text-align: center;">
<input type="text" style="width: 86%; height: 33px;margin: 20px;font-size:26px" id="div" value="0" disabled />
</div>
<div id="div1" style="text-align: center">
</div>
</div>
<script>
var value1 = "", value2 = "", value3="";
var array = new Array(" + ", " - ", " × ", " ÷ ", " = ", " . "," C ","+/-");//显示值
var Array1 = new Array("+", "-", "*", "/", "=", ".");//选中值
for (var i = 0; i < 18; i++)
{
var s = document.createElement("input");
document.getElementById("div1").appendChild(s);
var c = document.getElementById("div1").getElementsByTagName("input");
c[i].type = "button"; c[i].value = "" + i + ""; c[i].name = "undefined"; c[i].style = "width:55px;font-size:23px;font-weight:bolder;margin: 10px 10px;";
if (i >= 10)
{
var x=parseInt(i)-10;
c[i].type = "button"; c[i].value = "" + array[x] + ""; c[i].name = "" + Array1[x] + ""; c[i].style = "width:55px;font-size:23px;font-weight:bolder;margin: 10px 10px;";
}
}
var v = document.getElementById("div1").getElementsByTagName("input");
for (var i = 0; i < v.length; i++)
{
v[i].onclick=function () {
var value = this.value;
var values = this.name;
if (value == " C " || value == "+/-")
{
value1 = "";
value2 = "";
value3 = "";
document.getElementById("div").value = 0;
} else {
if (values == "undefined")
{
value1 += value;
value3 += value;
document.getElementById("div").value = value1;
} else {
if (values == "=") {
value2 = eval(value3);//计算 JS 字符串(例如eval("1+1") 结果:2)
value1 = value2;
document.getElementById("div").value = value2;
} else {
value1 += value;//显示
value3 += values;//内部计算
}
}
}
}
}
</script>
</body>
效果图: