用原生js做了一个计算器
做一个计算器,在前端上你需要一个css3美观布局,而我的布局还是比较简单,希望看了此文章读者,他在css3布局美观点。`
<script type="text/javascript">
var contexts=document.getElementsByClassName('context');
var ins=document.getElementsByClassName('in')[0];
var others=document.getElementsByClassName('other');
//这个for是先判断退格(DEL)和清零(C)
for(var i=0;i<others.length;i++) {
others[i].onclick=function() {
if(this.value=='C') {
ins.value=0;
}
if(this.value=='DEL') {
ins.value=ins.value.substr(0,ins.value.length-1);
if(ins.value.length==0) {
ins.value=0;
}
}
};
}
//这个for是数字和操作符的判断,先分为‘=’和‘!=’判断,之后由‘!=’分为数字和加减乘除操作费。
for(var j=0;j<contexts.length;j++) {
contexts[j].onclick=function() {
//ins.value="";
if(this.value!='=') {
ins.value+=this.value;
if(ins.value.charAt(0)==aa) {
ins.value="";
alert("请注意,第一个不能输入操作符号"+"+ - * /");
}//char(索引值),该函数是判断在该索引下该字符串是否为该字符
if(ins.value.charAt(0)=='0') {
ins.value=ins.value.substr(1,ins.value.length-1);
//substr(索引下标,长度),该函数是从索引下标开始到长度的截取的字符串
}
}
if(this.value=='=') {
ins.value+=this.value;
ins.value=ins.value.substr(0,ins.value.length-1);
//eval()函数是做运算。想看eval()函数的读者,请看下面的解释。
ins.value=eval(ins.value);
}
};
}
</script>
<style>
#total{width:320px;height:300px; margin:50px;border:solid #CC3 2px;}
.in{width:300px;height:40px; margin:10px;}
.context{width:50px;height:50px;margin:5px; font-size:25px;}
.other{height:50px;width:140px;margin:5px;font-size:25px;}
</style>
<html>
<head>
<meta charset="utf-8">
<title>计算器</title>
</head>
<body>
<div id="total">
<input type="text" class="in" value="0" >
<input type="button" class="context" value="7" >
<input type="button" class="context" value="8">
<input type="button" class="context" value="9">
<input type="button" class="context" value="+">
<input type="button" class="context" value="-">
<input type="button" class="context" value="4">
<input type="button" class="context" value="5">
<input type="button" class="context" value="6">
<input type="button" class="context" value="*">
<input type="button" class="context" value="/">
<input type="button" class="context" value="1">
<input type="button" class="context" value="2">
<input type="button" class="context" value="3">
<input type="button" class="context" value="0">
<input type="button" class="context" value="=">
<input type="button" class="other" value="DEL">
<input type="button" class="other" value="C">
</div>
</body>
</html>
这是我个人对eval()函数的理解,请看下面解释:
(1)直接输出
例子:var a=52; document.write(a); // 输出:“10”
(2)通过解析js代码(js代码必须是字符串类型)或者是进行计算(计算前提也必须是字符串类型)之后,输出最后值
例如本章代码:ins.value=ins.value.substr(0,ins.value.length-1);//这段代码是为获取要计算的字符串代码
ins.value=eval(ins.value);//这段代码是为进行计算所要计算字符串代码。
还有一个例子,var a="23"; document.write(eval(a));
//输出结果为"6";
其实我这个程序还是有很多bug,例如显示框的第一个字符不能显示加减乘除操作符符号,而我这里却出现这个问题,需要进行改进。如果大家觉得还有加很多功能或者你能实现很多功能的话,请你进行评论。
转载:https://blog.csdn.net/qq_43656995/article/details/101828993
查看评论