使用js来实现一个简单的计算器功能,包括加减乘除以及清空内容。
下面的HTML的代码:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="jisuandiv"> <h2>js计算器</h2> <input type="text" id="text" value="" disabled="disabled"/> <br> <div id="jisuankuang"> <button type="button" onclick="cale(this.id)" id="7" value="7">7</button> <button type="button" onclick="cale(this.id)" id="8" value="8">8</button> <button type="button" onclick="cale(this.id)" id="9" value="9">9</button> <button type="button" onclick="cale(this.id)" id="*" value="*">*</button> <button type="button" onclick="cale(this.id)" id="4" value="4">4</button> <button type="button" onclick="cale(this.id)" id="5" value="5">5</button> <button type="button" onclick="cale(this.id)" id="6" value="6">6</button> <button type="button" onclick="cale(this.id)" id="/" value="/">/</button> <button type="button" onclick="cale(this.id)" id="1" value="1">1</button> <button type="button" onclick="cale(this.id)" id="2" value="2">2</button> <button type="button" onclick="cale(this.id)" id="3" value="3">3</button> <button type="button" onclick="cale(this.id)" id="-" value="-">-</button> <button type="button" onclick="jieguo()" id="=" value="">=</button> <button type="button" onclick="cale(this.id)" id="0" value="0">0</button> <button type="button" onclick="C()" id="C" >C</button> <button type="button" onclick="cale(this.id)" id="+" value="+">+</button> </div> </div> </body> </html>
css代码:
#jisuandiv{
height: 460px;
width: 300px;
background: linear-gradient(to bottom, rgba(255,255,255,0.15) 0%, rgba(0,0,0,0.15) 100%), radial-gradient(at top center, rgba(255,255,255,0.40) 0%, rgba(0,0,0,0.40) 120%) #989898; background-blend-mode: multiply,multiply;
}
#jisuandiv>h2{
text-align: center;
}
#jisuandiv>input{
display: block;
height: 60px;
width: 260px;
line-height: 60px;
font-size: 40px;
margin: 0 auto;
text-align: center;
}
#jisuankuang{
margin: 0 auto;
height: 300px;
width: 260px;
border: white 4px solid;
display: flex;
flex-flow: row wrap;
justify-content: space-around;
}
#jisuankuang>button{
margin: 6px;
width: 50px;
height: 50px;
background: red;
font-size: 16px;
}```
js代码:
// 获取输入数字
function cale(num){
document.getElementById("text").value +=document.getElementById(num).value;
}
// 计算结果
function jieguo(){
var str= document.getElementById("text").value;
document.getElementById("text").value = eval(str);
}
function C(){
document.getElementById("text").value ="";
}
```
简单的功能,希望能帮助到需要的人,这里代码的重点是运用js中的函数 eval
,它主要可以让string字符串进行计算,例如:eval("2+2");
其他功能只要能获得按钮的参数,并累加给显示的位置即可。