本文实例为大家分享了javascript实现简易的计算器的具体代码,供大家参考,具体内容如下
javascript实现简易计算器,只有两个input输入框,简单实现加减乘除:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>简易计算器</title>
</head>
<style>
body{
border: 2px #00FFFF;
}
</style>
<body background="img/2.jpg" style="background-repeat: no-repeat;margin-left: 10px;">
<p>
<h1>简易计算器</h1>
<input type="text" id="num1" width="50px" />
<select id="select">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id="num2" width="50px"/>
<br />
<input type="button" value="计算" onclick="cal()" style="color: #FF0000;"/>
<input id="result"></input>
</p>
</body>
<script type="text/javascript">
function cal(){
var num1=document.getElementById("num1").value;
var num2=document.getElementById("num2").value;
var c = document.getElementById("select").value;
num1=parseFloat(num1);
num2=parseFloat(num2);
switch(c){
case "+":
document.getElementById("result").value=parseInt(num1)+parseInt(num2);
break;
case "-":
document.getElementById("result").value=parseInt(num1)-parseInt(num2);
break;
case "*":
document.getElementById("result").value=parseInt(num1)-parseInt(num2);
break;
case "/":
document.getElementById("result").value=parseInt(num1)/parseInt(num2);
break;
}
}
</script>
</html>
效果截图:
JavaScript eval() 函数实现计算器:只有一个input输入框:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>简易计算器</title>
</head>
<body background="img/2.jpg" style="background-repeat: no-repeat;margin-left: 10px;">
<h1>简易计算器</h1>
<p>
<input type="text" id="num1"/>
<input type="button" value="计算" onclick="cal()" />
</p>
<p>
<span id="result" style="color: #FF0000;">计算结果:</span>
</p>
</body>
<script type="text/javascript">
function cal(){
var num1=document.getElementById("num1").value;
var result=document.getElementById("result");
try{
//有值就计算
var res=eval("("+num1+")");
result.innerHTML=res;
}catch(e){
console.log(e);
result.innerHTML="表达式异常";
}
}
</script>
</html>
实现效果:
body里面的背景图片设置:
background-repeat: no-repeat;图片原大小
background-size:100%; 图片全铺满