2 计算器
<html>
<head>
<title>计算器</title>
<meta charset="gbk"/>
<style type="text/css">
div{
border:1px solid;
padding:10px;
}
#div0{
width:1000px;
height:600px;
position:absolute;
top:100px;
left:450px;
}
#divtop{
width:600px;
height:150px;
position:absolute;
top:50px;
left:200px;
text-align:center;
}
#divleft,#divright{
height:300px;
position:absolute;
top:240px;
}
#divleft{
width:350px;
left:150px;
}
#divright{
right:150px;
width:260px;
}
#span_text{
font-size:70px;
letter-spacing:90px;
font-weight:bold;
color:blue;
text-indent:50px;
}
#text_show,#but_clear{
font-size:40px;
}
#divleft input,#divright input{
width:55px;
height:55px;
font-size:30px;
font-weight:bold;
}
#divleft input{
margin:40px 6px;
}
#divright input{
margin:40px 14px;
}
</style>
</head>
<body>
<div id="div0">
<div id="divtop">
<span id="span_text"> 计算器</span><br/>
<input type="text" id="text_show" disabled="disabled"/>
<input type="button" id="but_clear" value="清空" style="color:red;"/>
</div>
<div id="divleft">
</div>
<div id="divright">
</div>
</div>
<script type="text/javascript">
var strRight="+-×÷.=";
var oText;
window.onload=function(){
var odivLeft=document.getElementById("divleft");
oText=document.getElementById("text_show");
var odivRight=document.getElementById("divright");
for(var i=0;i<=9;i++){
var oBut=document.createElement("input");
odivLeft.appendChild(oBut);
oBut.type="button";
oBut.value=i;
oBut.onclick=function(){
setNum(this.value);
}
}
for(var i=0;i<strRight.length;i++){
var oBut=document.createElement("input");
odivRight.appendChild(oBut);
oBut.type="button";
oBut.value=strRight.charAt(i);
oBut.onclick=function(){
if(this.value=="."){
setNum(this.value);
}else if(this.value=="="){
getResult();
}else{
setYsf(this.value);
}
}
}
document.getElementById("but_clear").onclick=jsqClear;
}
var num1="",num2="",ysf="";
function setNum(n){
if(ysf){
if(n=="."){
if(num2.indexOf(".")!=-1){
alert("一个数字只能偶一个小数点!");
return;
}
}
num2+=n;
}else{
if(n=="."){
if(num1.indexOf(".")!=-1){
alert("一个数字只能偶一个小数点!");
return;
}
}
num1+=n;
}
oText.value=num1+""+ysf+""+num2;
}
function getResult(){
if(!num2){
alert("数据不完整 不能运算!");
return;
}
var fnum1=parseFloat(num1);
var fnum2=parseFloat(num2);
var result="";
switch(ysf){
case "+":
result=fnum1+fnum2;break;
case "-":
result=fnum1-fnum2;break;
case "×":
result=fnum1*fnum2;break;
case "÷":
result=fnum1/fnum2;break;
}
result=parseInt(result*100)/100;
oText.value=num1+""+ysf+""+num2+"="+result;
}
function jsqClear(){
num1="";num2="";ysf="";
oText.value="";
}
function setYsf(y){
if(ysf){
alert("运算符只能赋值一次!");
return;
}
ysf=y;
oText.value=num1+""+ysf+""+num2;
}
</script>
</body>
</html>