<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Js计算器</title>
<style>
*{
margin: 0px;
padding: 0px;
}
.box{
margin: 100px auto;
270px;
border: 1px solid black;
padding: 20px;
}
.keys{
overflow: hidden;
padding: 10px;
}
.keys span{
float: left;
height: 30px;
50px;
margin-left: 10px;
margin-top: 10px;
line-height: 30px;
text-align: center;
background: #ccc;
box-shadow: 2px 2px 2px 2px black; /*盒阴影x偏移量,y偏移量,Bulr模糊程度(半径)**/
}
.outShow p{
100%;
display: block;
height: 80px;
border: none;
/*border: 1px solid #ccc;*/
background: black;
color: white;
text-align: right;
line-height: 80px;
font-size: 40px;
}
.keys span:last-child{
110px;
}
.keys span:hover{
background: #ecf;
}
</style>
</head>
<body>
<div class="box">
<div class="outShow">
<p id="outShow"></p>
</div>
<div class="keys" id="keys">
<span>AC</span>
<span>DEL</span>
<span>+</span>
<span>/</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span>*</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span>-</span>
<span>3</span>
<span>2</span>
<span>1</span>
<span>sd</span>
<span>0</span>
<span>.</span>
<span>=</span>
</div>
</div>
</body>
<script>
var outShow=document.getElementById("outShow");
var keys=document.getElementById("keys");
var spans=keys.getElementsByTagName("span");
for(var i=0;i<spans.length;i++){
spans[i].onclick=function(){
var getvalue=spans[i].innerHTML;
dealCount(getvalue);
alert(getvalue);
}
}
function dealCount(count){
switch(count){
case "=":
break;
case "+":
break;
case "-":
break;
case "*":
break;
case "/":
break;
default:
outShow.innerHTML=outShow.innerHTML+count.innerHTML;
break;
}
}
var outShow = document.getElementById("outShow");
var spans = document.getElementById("keys").getElementsByTagName("span");
var sNum1="";
var op="";
var isNeedClear=false;
//给所有按钮添加点击事件
for(i=0;i<spans.length;i++){
spans[i].onclick=function(){
dealCount(this.innerHTML);
}
}
//实现点击事件
function dealCount(inpuvalue){
switch(inpuvalue){
case "=":
var sNum2=outShow.innerHTML;
optionsall(sNum1,sNum2,op);
break;
case "+":
case "-":
case "*":
case "/":
sNum1=outShow.innerHTML;
op=inpuvalue;
outShow.innerHTML=op;
isNeedClear=true;
break;
//清空键的功能实现
case "AC":
outShow.innerHTML="";
break;
//删除键的功能实现
case "DEL":
delNum=outShow.innerHTML
outShow.innerHTML=delNum.substring(0,delNum.length-1);
break;
default:
if(isNeedClear==false){
outShow.innerHTML=outShow.innerHTML+inpuvalue;
}else{
outShow.innerHTML=inpuvalue;
isNeedClear=false;
}
}
}
//实现加减乘除功能
function optionsall(sNum1,sNum2,op){
switch(op){
case "+":
outShow.innerHTML=parseFloat(sNum1)+parseFloat(sNum2);
break;
case "-":
outShow.innerHTML=parseFloat(sNum1)-parseFloat(sNum2);
break;
case "*":
outShow.innerHTML=parseFloat(sNum1)*parseFloat(sNum2);
break;
case "/":
outShow.innerHTML=parseFloat(sNum1)/parseFloat(sNum2);
break;
}
}
</script>
</html>