首页 > 代码库 > 计算器的简单实现
计算器的简单实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算器</title>
<style id="jsbin-css">
div,span{
margin:0;padding:0;
font-weight:bold;
font: bold 16px Arial, sans-serif;
/*禁止选中文本*/
-moz-user-select:none;
-webkit-user-select:none;
-o-user-select:none;
user-select:none;
}
body{
background:radial-gradient(circle,#fff,#aaa);
background:-webkit-radial-gradient(circle,#fff,#aaa);
background:-o-radial-gradient(circle,#fff,#aaa);
background:-moz-radial-gradient(circle,#fff,#aaa);
background-size:cover;
}
#calculator{
width:325px;
height:auto;
margin:100px auto;
padding:20px;
background:linear-gradient(#9dd2ea, #8bceec);
background:-o-linear-gradient(#9dd2ea, #8bceec);
background:-webkit-linear-gradient(#9dd2ea, #8bceec);
background:-moz-linear-gradient(#9dd2ea, #8bceec);
border-radius:5px;
box-shadow:0 7px 8px #0000ff
}
.keys,.head{overflow:hidden;}
.keys span,.clear{
float:left;
width:66px;
height:40px;
margin:0 5px 10px 8px;
text-align:center;
line-height:40px;
border-radius:3px;
background:#eee;
box-shadow:0 5px 1px #999;
cursor:pointer;
transition:all 0.3s ease;
}
.keys span:hover{
background:#87cefa;
box-shadow:0 5px 1px #1e90ff;
color:#fff;
}
.keys .sign{
background:#fffacd;
}
.clear{
float:left;
background:#ffb6c1;
box-shadow:0 5px 1px #ff86c1;
}
.clear:hover{
background:#ff96a1;
box-shadow:0 5px 1px #ff4691;
color:#fff;
}
.show{
width:213px;
height:40px;
float:right;
margin:0 16px 5px 0;
border-radius:3px;
background:#999;
font-size:20px;
line-height:40px;
text-align:right;
padding-right:10px;
box-shadow:inset 0 4px 5px #333;
}
</style>
</head>
<body>
<div id="calculator">
<div class="head">
<!-- 清除 -->
<span class="clear">c</span>
<!-- 计算结果 -->
<div class="show" id="show"></div>
</div>
<!-- 按键 -->
<div class="keys">
<span>7</span>
<span>8</span>
<span>9</span>
<span class="sign">+</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span class="sign">-</span>
<span>1</span>
<span>2</span>
<span>3</span>
<span class="sign">*</span>
<span>0</span>
<span>.</span>
<span>=</span>
<span class="sign">/</span>
</div>
</div>
<script>
function getComputer(){
//第一步:获取页面上所有的按键
var getKey=document.getElementById(‘calculator‘).getElementsByTagName(‘span‘);
//第二步:获取输出框
var show=document.getElementById(‘show‘);
//第三步:循环遍历数组元素
for(var i=0;i<getKey.length;i++){
//第四步:每点击一个数字需要出发一次计算操作,因此需要一个点击函数
getKey[i].onclick=function(){
//第五步:获取到当前点击的数字值,因为当前获取的对象是span值,因此获取内容需要innerHTML而不是value
var oKey=this.innerHTML;
//第六步:获取输出框的值
var showValue=http://www.mamicode.com/show.innerHTML;
// show.innerHTML=oKey;
// alert(show.innerHTML)
//第七步:判断特殊按键的值
//如果按键是c,输出空字符串
if(oKey==‘c‘){
show.innerHTML=‘‘;
}
//如果按键是=,运算输入的数字,并赋值给show,此处用到eval方法
else if(oKey==‘=‘){
var result=eval(showValue);
show.innerHTML=result;
}
//如果按键是数字,正常输出数字到show框
else
// alert(oKey);
show.innerHTML+=oKey;
}
}
}
getComputer();
//检查 JScript 代码并执行
// alert(eval(‘3+4‘)); 计算此方法内的数值,将字符串强制转换成数值
</script>
</html>
计算器的简单实现