1.首先我们要做好一个计算器的界面,主要用到html与css的知识,下面是代码
<table id="calculater" onClick="calculater()">
<tr>
<td id="display" colspan="5">0</td>
</tr>
<tr>
<td class="numberkey" >1</td>
<td class="numberkey" >2</td>
<td class="numberkey" >3</td>
<td class="numberkey" >+</td>
<td class="numberkey" id="deletesign">c</td>
</tr>
<tr>
<td class="numberkey" >4</td>
<td class="numberkey" >5</td>
<td class="numberkey" >6</td>
<td class="numberkey" >-</td>
<td rowspan="3" id="equality" onclick="resultscalcaulte()">=</td>
</tr>
<tr>
<td class="numberkey" >7</td>
<td class="numberkey" >8</td>
<td class="numberkey" >7</td>
<td class="numberkey" >*</td>
</tr>
<tr >
<td class="numberkey" >+/-</td>
<td class="numberkey" >0</td>
<td class="numberkey" >.</td>
<td class="numberkey" >/</td>
</tr>
上面设置一个简单的table表格,主要内容是计算器的数字键盘和符号,还有就是class名和ID名,函数名,主要是用作css样式设计和javascript程序设计,后面会用到,就先贴出来了
colspan="5" 是合并五列的意思,表示这个单元格要占五列
rowspan="3"是合并三行的意思,表示这个单元格要占三行
效果如下,这样一个简单的架构就完成了
2.接下来就是css的设计,下面是代码
*{
padding:0
margin:1px
}
#calculater{
margin: auto
margin-top: 30px
border: solid 6px #2371D3
border-spacing: 0px
}
#display{
width: 100%
height: 30px
border-bottom: solid 4px #2371D3
font-weight: bold
color: #193D83
font-family: 黑体
padding-left: 2px
}
.numberkey{
cursor: pointer
width: 40px
height: 30px
border: solid 1px #FFFFFF
background: #2371D3
color: #ffffff
text-align: center
font-weight: bold
font-family: 黑体
}
#equality{
cursor: pointer
width: 40px
height: 100%
background: #2371D3
border: solid 1px #FFFFFF
color: #ffffff
text-align: center
font-weight: bold
font-family: 黑体
}
.numberkey:hover{
background: #EA6F30
}
#equality:hover{
background: #EA6F30
}
以上是css代码,比较简单
border-spacing: 0px
这里代码的意义是:table中单元格与单元格,表格边缘都有默认距离,这里border-spacing: 0px能使其默认距离为零,没有这句会比较难设计好看的样式。
cursor: pointer
这里代码的意义是:使鼠标放在上面时变成一个手的标志
效果如下
3.接下来是javascript的代码,按照思路来一点点写
首先我们要设计,当鼠标点击某个单元格时我们能获取这个单元格上的内容,即数字或符号
所以我们在table标签里加上onClick="calculater()",添加一个点击事件
然后用event.srcElement.innerText获取单元格上的内容,event是事件的意思,在这里这个事件当然是点击了,srcElement就是事件的元素,在这里是被点击的单元格,innerText是获取这个单元格的内容。
这里我们就可以写出这个函数第一行代码,获取被点击的单元格的内容
function calculater(){
results=event.srcElement.innerText
}
results就是单元格的内容
4.当然获取了什么要显示在第一个单元格那里,这里我们还是用innerText,来输出这个点击的值
display.innerText=results
这里代码的意义是:display是第一格单元格的id,就是在第一行显示你点击了什么
calculater()的代码就变成这样
function calculater(){
results=event.srcElement.innerText
display.innerText=results
}
这样我们就能输出我们点击的单元格内容
5.但这样我们只能输出一次单击的内容,为了把内容串起来,我们把代码改为
var results=""
function calculater(){
results+=event.srcElement.innerText
display.innerText=results
}
设置results为全局变量,event.srcElement.innerText用+=累加进results,
这样我们就能输入并显示一条算式
6.我们在“=”单元格标签里加上onClick="resultscalcaulte()",计算这个结果
function resultscalcaulte(){
calresults=eval(results)
display.innerText=calresults
}
eval()能运行括号里的javascript语句的字符串,并返回其值,如果results等于7+8,那eval就会计算7+8,并返回56,然后后面一条代码把56显示出来
7.加入上面的运算后,还是无法显示结果,原因是点击“=”单元格会先触发resultscalcaulte()函数,再触发calculater()函数,所以我们在resultscalcaulte()得到的结果就被calculater()的结果覆盖了,我们需要再在calculater()里加上
if (event.srcElement.innerText=="=") {
return
}
使点击“=”单元格触发的calculater()函数得不到任何结果
最后得到最简单的计算器运算代码
var results=""
var calresults=""
function calculater(){
if (event.srcElement.innerText=="=") {
return
}
results+=event.srcElement.innerText
display.innerText=results
}
function resultscalcaulte(){
calresults=eval(results)
display.innerText=calresults
}
8.下面是计算7*8的结果
<html><head>
<title>计算器</title>
</head>
<body bgcolor="#ffffff" onload="FKeyPad.ReadOut.focus()FKeyPad.ReadOut.select()">
<FORM name="Keypad" action="">
<TABLE align="center">
<B>
<TABLE align="center" border=2 width=50 height=60 cellpadding=1 cellspacing=5>
<TR>
<TD colspan=3 align=middle><input name="ReadOut" type="Text" onkeypress="CheckOut()" size=24 value="0"
width=100%></TD>
<TD></TD>
<TD><input name="btnClear" type="Button" value=" C " onclick="Clear()"></TD>
<TD><input name="btnClearEntry" type="Button" value=" CE " onclick="ClearEntry()"></TD>
</TR>
<TR>
<TD><input name="btnSeven" type="Button" value=" 7 " onclick="NumPressed(7)"></TD>
<TD><input name="btnEight" type="Button" value=" 8 " onclick="NumPressed(8)"></TD>
<TD><input name="btnNine" type="Button" value=" 9 " onclick="NumPressed(9)"></TD>
<TD></TD>
<TD><input name="btnNeg" type="Button" value=" +/- " onclick="Neg()"></TD>
<TD><input name="btnPercent" type="Button" value=" % " onclick="Percent()"></TD>
</TR>
<TR>
<TD><input name="btnFour" type="Button" value=" 4 " onclick="NumPressed(4)"></TD>
<TD><input name="btnFive" type="Button" value=" 5 " onclick="NumPressed(5)"></TD>
<TD><input name="btnSix" type="Button" value=" 6 " onclick="NumPressed(6)"></TD>
<TD></TD>
<TD align=middle><input name="btnPlus" type="Button" value=" + " onclick="Operation('+')"></TD>
<TD align=middle><input name="btnMinus" type="Button" value=" - " onclick="Operation('-')"></TD>
</TR>
<TR>
<TD><input name="btnOne" type="Button" value=" 1 " onclick="NumPressed(1)"></TD>
<TD><input name="btnTwo" type="Button" value=" 2 " onclick="NumPressed(2)"></TD>
<TD><input name="btnThree" type="Button" value=" 3 " onclick="NumPressed(3)"></TD>
<TD></TD>
<TD align=middle><input name="btnMultiply" type="Button" value=" * " onclick="Operation('*')"></TD>
<TD align=middle><input name="btnDivide" type="Button" value=" / " onclick="Operation('/')"></TD>
</TR>
<TR>
<TD><input name="btnZero" type="Button" value=" 0 " onclick="NumPressed(0)"></TD>
<TD><input name="btnDecimal" type="Button" value=" . " onclick="Decimal()"></TD>
<TD colspan=2></TD>
<TD><input name="btnEquals" type="Button" value=" = " onclick="Operation('=')"></TD>
<TD><input name="btnReturn" type="Button" value="返 回" onclick="goReturn()"></TD>
</TR>
</TABLE>
</TABLE>
</B>
</FORM>
</CENTER>
<font face="Verdana, Arial, Helvetica" size=2>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var FKeyPad = document.forms['Keypad']
var Accum = "0"
var FlagNewNum = false
var PendingOp = ""
//===============================================================================
//[描述] 浮点数精确计算
//[参数] str1 - 第一个数
// str2 - 第二个数
// type - 运算符
// precision - 小数位精度
//[调用方式] longCount(str1,str2,type,precision)
//[返回值] 计算结果
//===============================================================================
function longCount(str1,str2,type) {
var comma1 = 0
if (str1.indexOf(".")!=-1) {
str1 = str1.replace(/0*$/,"")
comma1 = str1.length - str1.indexOf(".")-1
}
var comma2 = 0
if (str2.indexOf(".")!=-1) {
str2 = str2.replace(/0*$/,"")
comma2 = str2.length - str2.indexOf(".")-1
}
str1 = str1.replace(/\./,"")
str2 = str2.replace(/\./,"")
var value,comma
if (type!="*") {
if (comma1>comma2) {
for (var i=0i<comma1-comma2i++) str2 += "0"
comma = (type=="/")?0:comma1
}else {
for (var i=0i<comma2-comma1i++) str1 += "0"
comma = (type=="/")?0:comma2
}
}else {
comma = comma1 + comma2
}
if (type=="+") {
value = parseInt(str1,10) + parseInt(str2,10)
}else if (type=="-") {
value = parseInt(str1,10) - parseInt(str2,10)
}else if (type=="*") {
value = parseInt(str1,10) * parseInt(str2,10)
}else if (type=="/") {
value = parseInt(str1,10) / parseInt(str2,10)
}
value = String(value)
if (comma>0) value = value.substring(0,value.length-comma)+"."+value.substring(value.length-
comma,value.length)
if (value.indexOf(".")!=-1)
value = value.replace(/0*$/,"")
return value
}
function NumPressed (Num) {
if (FlagNewNum) {
FKeyPad.ReadOut.value = Num
FlagNewNum = false
}
else {
if (FKeyPad.ReadOut.value == "0")
FKeyPad.ReadOut.value = Num
else
FKeyPad.ReadOut.value += Num
}
}
function Operation (Op) {
var Readout = FKeyPad.ReadOut.value
if (FlagNewNum &&PendingOp != "=")
else
{
FlagNewNum = true
if ( '+' == PendingOp || '-' == PendingOp || '/' == PendingOp || '*' == PendingOp)
Accum = longCount(Accum,Readout,PendingOp)
else
Accum = Readout
FKeyPad.ReadOut.value = Accum
PendingOp = Op
FKeyPad.ReadOut.focus()
FKeyPad.ReadOut.select()
}
}
function Decimal () {
var curReadOut = FKeyPad.ReadOut.value
if (FlagNewNum) {
curReadOut = "0."
FlagNewNum = false
}
else
{
if (curReadOut.indexOf(".") == -1)
curReadOut += "."
}
FKeyPad.ReadOut.value = curReadOut
}
function ClearEntry () {
FKeyPad.ReadOut.value = "0"
FlagNewNum = true
}
function Clear () {
Accum = "0"
PendingOp = ""
ClearEntry()
}
function Neg () {
alert(FKeyPad.ReadOut.value)
FKeyPad.ReadOut.value = longCount(FKeyPad.ReadOut.value,"-1","*")
}
function Percent () {
FKeyPad.ReadOut.value = longCount(FKeyPad.ReadOut.value,Accum,"*")
FKeyPad.ReadOut.value = longCount(FKeyPad.ReadOut.value,100,"/")
}
function goReturn() {
top.returnValue = FKeyPad.ReadOut.value
self.close()
}
function CheckOut() {
var keyCode = window.event.keyCode
if (keyCode>=48 &&keyCode<=57) {
if (FlagNewNum) {
FKeyPad.ReadOut.value = ""
//window.event.keyCode = null
FlagNewNum = false
}
return true
}else if (keyCode==43 || keyCode==45 || keyCode==42 || keyCode==47 || keyCode==61) {
Operation(String.fromCharCode(keyCode))
}else if (keyCode==46) {//.
if (FKeyPad.ReadOut.value.indexOf(".") == -1)
return true
}else if (keyCode==13) goReturn()
window.event.returnValue = false
return false
}
// End -->
</SCRIPT>
</body>
</html>
首先,由于JS的存在数值的精度误差问题:
0.1+0.2 //0.30000000000000004
0.3-0.1 //0.19999999999999998
所以在编写计算器是应首先解决计算精度问题,以下四个代码段分别是js中精确的加减乘除运算函数
//浮点数加法运算
function floatAdd(arg1,arg2){
var r1,r2,m
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2))
return (arg1*m+arg2*m)/m
}
//浮点数减法运算
function floatSub(arg1,arg2){
var r1,r2,m,n
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2))
//动态控制精度长度
n=(r1>=r2)?r1:r2
return ((arg1*m-arg2*m)/m).toFixed(n)
}
//浮点数乘法运算
function floatMul(arg1,arg2){
var m=0,s1=arg1.toString(),s2=arg2.toString()
try{m+=s1.split(".")[1].length}catch(e){}
try{m+=s2.split(".")[1].length}catch(e){}
return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}
//浮点数除法运算
function floatDiv(arg1,arg2) {
var t1 = 0, t2 = 0, r1, r2
try {t1 = arg1.toString().split(".")[1].length} catch (e) {}
try {t2 = arg2.toString().split(".")[1].length} catch (e) {}
with (Math) {
r1 = Number(arg1.toString().replace(".", ""))
r2 = Number(arg2.toString().replace(".", ""))
return (r1 / r2) * pow(10, t2 - t1)
}
}
以下是详细的计算器代码:
HTML5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>简单计算器</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<div id="calculator">
<div id="calculator_container">
<h3>计算器</h3>
<table id="calculator_table">
<tbody>
<tr>
<td colspan="5">
<input type="text" id="resultIpt" readonly="readonly" value="" size="17" maxlength="17" style="width:294pxcolor: black">
</td>
</tr>
<tr>
<td><input type="button" value="←" class="btn_color1 btn_operation"></td>
<td><input type="button" value="全清" class="btn_color1 btn_operation"></td>
<td><input type="button" value="清屏" class="btn_color1"></td>
<td><input type="button" value="﹢/﹣" class="btn_color2 btn_operation"></td>
<td><input type="button" value="1/×" class="btn_color2 btn_operation"></td>
</tr>
<tr>
<td><input type="button" value="7" class="btn_color3 btn_number"></td>
<td><input type="button" value="8" class="btn_color3 btn_number"></td>
<td><input type="button" value="9" class="btn_color3 btn_number"></td>
<td><input type="button" value="÷" class="btn_color4 btn_operation"></td>
<td><input type="button" value="%" class="btn_color2 btn_operation"></td>
</tr>
<tr>
<td><input type="button" value="4" class="btn_color3 btn_number"></td>
<td><input type="button" value="5" class="btn_color3 btn_number"></td>
<td><input type="button" value="6" class="btn_color3 btn_number"></td>
<td><input type="button" value="×" class="btn_color4 btn_operation"></td>
<td><input type="button" value="√" class="btn_color2 btn_operation"></td>
</tr>
<tr>
<td><input type="button" value="1" class="btn_color3 btn_number"></td>
<td><input type="button" value="2" class="btn_color3 btn_number"></td>
<td><input type="button" value="3" class="btn_color3 btn_number"></td>
<td><input type="button" value="-" class="btn_color4 btn_operation"></td>
<td rowspan="2">
<input type="button" value="=" class="btn_color2" style="height: 82px" id="simpleEqu">
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="0" class="btn_color3 btn_number" style="width:112px">
</td>
<td><input type="button" value="." class="btn_color3 btn_number" ></td>
<td><input type="button" value="+" class="btn_color4 btn_operation"></td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="calculator.js"></script>
</body>
</html>
CSS3
* {
margin: 0
padding: 0
}
#calculator{
position: relative
margin: 50px auto
width: 350px
height: 400px
border: 1px solid gray
-webkit-border-radius: 10px
-moz-border-radius: 10px
border-radius: 10px
-webkit-box-shadow: 2px 2px 4px gray
-moz-box-shadow: 2px 2px 4px gray
box-shadow: 2px 2px 4px gray
behavior:url("ie-css3.htc") /*IE8-*/
}
#calculator_table{
position: relative
margin: 10px auto
border-collapse:separate
border-spacing:10px 20px
}
h3{
position: relative
width: 60px
height: 30px
margin: 0 auto
}
#calculator_table td{
width: 50px
height: 30px
border: 1px solid gray
-webkit-border-radius: 2px
-moz-border-radius: 2px
border-radius: 2px
behavior:url("ie-css3.htc") /*IE8-*/
}
#calculator_table td input{
font-size: 16px
border: none
width: 50px
height: 30px
color: white
}
input.btn_color1{
background-color: orange
}
input.btn_color2{
background-color: #133645
}
input.btn_color3{
background-color: #59807d
}
input.btn_color4{
background-color: seagreen
}
input:active{
-webkit-box-shadow: 3px 3px 3px gray
-moz-box-shadow: 3px 3px 3px gray
box-shadow: 3px 3px 3px gray
behavior:url("ie-css3.htc") /*IE8-*/
}
JS
window.onload=function() {
var resultIpt = document.getElementById("resultIpt")//获取输出文本框
var btns_number = document.getElementsByClassName("btn_number")//获取数字输入按钮
var btns_operation = document.getElementsByClassName("btn_operation")//获取 *** 作按钮
var simpleEqu = document.getElementById("simpleEqu")//获取"="按钮
var temp = ""
var num1= 0,num2=0
//获取第一个数
for(var i=0i<btns_number.lengthi++){
btns_number[i].onclick=function (){
temp += this.value
resultIpt.value = temp
}
}
//对获取到的数进行 *** 作
for(var j=0j<btns_operation.lengthj++) {
btns_operation[j].onclick = function () {
num1=parseFloat(resultIpt.value)
oper = this.value
if(oper=="1/×"){
num1 = Math.pow(num1,-1)//取倒数
resultIpt.value = num1.toString()
}else if(oper=="﹢/﹣"){ //取相反数
num1 = -num1
resultIpt.value = num1.toString()
}else if(oper=="√"){ //取平方根
num1 =Math.sqrt(num1)
resultIpt.value = num1.toString()
}else if(oper=="←"){ //删除个位
resultIpt.value = resultIpt.value.substring(0, resultIpt.value.length - 1)
}else if(oper=="全清"){ //清除数字
resultIpt.value = ""
}
else{ //oper=="+" "-" "×" "÷" "%"时,继续输入第二数字
temp = ""
resultIpt.value = temp
}
}
}
//输出结果
simpleEqu.onclick=function(){
num2=parseFloat(temp) //取得第二个数字
calculate(num1, num2, oper)
resultIpt.value = result.toString()
}
}
//定义一个计算函数
function calculate(num1, num2, oper) {
switch (oper) {
case "+":
result=floatAdd(num1, num2)//求和
break
case "-":
result=floatSub(num1, num2)//求差
break
case "×":
result=floatMul(num1, num2) //求积
break
case "÷":
result=floatDiv(num1, num2) //求商
break
case "%":
result=num1%num2 //求余数
break
}
}
//精确计算
//浮点数加法运算
function floatAdd(arg1,arg2){
var r1,r2,m
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2))
return (arg1*m+arg2*m)/m
}
//浮点数减法运算
function floatSub(arg1,arg2){
var r1,r2,m,n
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2))
//动态控制精度长度
n=(r1>=r2)?r1:r2
return ((arg1*m-arg2*m)/m).toFixed(n)
}
//浮点数乘法运算
function floatMul(arg1,arg2){
var m=0,s1=arg1.toString(),s2=arg2.toString()
try{m+=s1.split(".")[1].length}catch(e){}
try{m+=s2.split(".")[1].length}catch(e){}
return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}
//浮点数除法运算
function floatDiv(arg1,arg2) {
var t1 = 0, t2 = 0, r1, r2
try {t1 = arg1.toString().split(".")[1].length} catch (e) {}
try {t2 = arg2.toString().split(".")[1].length} catch (e) {}
with (Math) {
r1 = Number(arg1.toString().replace(".", ""))
r2 = Number(arg2.toString().replace(".", ""))
return (r1 / r2) * pow(10, t2 - t1)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)