JavaScript实现的极简计算器
计算器都是熟悉的那就废话不多说直接上效果图给各位看看。
最顶显示我们按键的结果,下面的框显示计算结果。
主要代码如下:
css
#jisuanqi{
margin: 0 auto;
width: 25%;
height: 280px;
border: 1px solid #DDD;
}
#shownumber{
text-align: right;
text-indent: 10px;
margin: 0 auto;
width: 90%;
height: 20px;
padding: 13px 0;
}
button{
border: 1px solid #DDD;
text-align: center;
width: 60px;
height: 30px;
padding: 0;
}
#show{
height: 50px;
border: 1px solid #DDD;
text-align: right;
}
html
<div id="jisuanqi" >
<div id="shownumber"></div>
<table cellspacing="10" width="280" align="center">
<tr>
<td colspan="4" id="show"></td>
</tr>
<tr>
<td><button onclick="numshow(this.id)" id="7" value="7">7</button></td>
<td><button onclick="numshow(this.id)" id="8" value="8">8</button></td>
<td><button onclick="numshow(this.id)" id="9" value="9">9</button></td>
<td><button onclick="numshow(this.id)" id="/" value="/">/</button></td>
</tr>
<tr>
<td><button onclick="numshow(this.id)" id="4" value="4">4</button></td>
<td><button onclick="numshow(this.id)" id="5" value="5">5</button></td>
<td><button onclick="numshow(this.id)" id="6" value="6">6</button></td>
<td><button onclick="numshow(this.id)" id="*" value="*">*</button></td>
</tr>
<tr>
<td><button onclick="numshow(this.id)" id="1" value="1">1</button></td>
<td><button onclick="numshow(this.id)" id="2" value="2">2</button></td>
<td><button onclick="numshow(this.id)" id="3" value="3">3</button></td>
<td><button onclick="numshow(this.id)" id="-" value="-">-</button></td>
</tr>
<tr>
<td><button onclick="numshow(this.id)" id="0" value="0">0</button></td>
<td><button onclick="tonull()" id="clear">clear</button></td>
<td><button onclick="result()" id="re">=</button></td>
<td><button onclick="numshow(this.id)" id="+" value="+">+</button></td>
</tr>
</table>
</div>
js代码如下:
function numshow(num){
var n = document.getElementById('shownumber');
var shuzi = document.getElementById(num).value;
n.innerHTML+=shuzi;
}
function result(){
var n = document.getElementById('show');
var re = eval(document.getElementById('shownumber').innerText);
n.innerHTML=re;
}
function tonull(){
var n = document.getElementById('shownumber');
n.innerHTML='';
var re = document.getElementById('show');
re.innerHTML='';
}
有错误和建议欢迎表示,万分感激!
此至,互勉!