JavaScript 简单计算器效果

快乐打工仔 分类:实例代码

分享一个非常简单的计算器效果,它能够实现简单的运算功能。

主要目的是学习一下相关的JavaScript基础知识,本站还有更多的计算器功能的代码,可以在特效代码板块中查找。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>犀牛前端部落</title>
<style type="text/css">
#box {
width: 300px;
height: 350px;
background: greenyellow;
overflow: hidden;
}
#int {
width: 250px;
display: block;
border: 0px;
height: 50px;
background-color: #fff;
margin: 20px auto 20px auto;
font-size: 24px;
color: greenyellow;
text-align: right;
padding-right: 10px;
}
#box-div {
width: 280px;
margin: 0 auto;
}
.box-ul {
list-style: none;
margin: 0;
padding: 0;
}
.box-li {
width: 50px;
height: 50px;
margin-left: 15px;
background: #f5f5f5;
color: yellowgreen;
list-style: none;
float: left;
margin-bottom: 10px;
font-size: 24px;
text-align: center;
line-height: 50px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box">
<input type="text" id="int" value="0">
<div id="box-div">
<ul class="box-ul">
<li class="box-li" value="7">7</li>
<li class="box-li" value="8">8</li>
<li class="box-li" value="9">9</li>
<li class="box-li" value="+">+</li>
<li class="box-li" value="4">4</li>
<li class="box-li" value="5">5</li>
<li class="box-li" value="6">6</li>
<li class="box-li" value="-">-</li>
<li class="box-li" value="1">1</li>
<li class="box-li" value="2">2</li>
<li class="box-li" value="3">3</li>
<li class="box-li" value="*">*</li>
<li class="box-li" value="0">0</li>
<li class="box-li" value="c">c</li>
<li class="box-li" value="=">=</li>
<li class="box-li" value="/">/</li>
</ul>
</div>
</div>
<script type="text/javascript">
(function() {
var sNum1 = '';
var sOpt = '';
var bNeedClear = false; //是否要清除输入框的内容
var boxDiv = document.getElementById("box-div"),
boxLi = boxDiv.getElementsByTagName("li");
for (var i = 0; i < boxLi.length; i++) {
boxLi[i].onclick = doInput;
}
function doInput() {
var int = document.getElementById("int");
var sHtml = this.innerHTML.replace("", "");
switch (sHtml) {
case "=":
int.value = result(parseInt(sNum1), parseInt(int.value), sOpt);
sNum1 = '';
sOpt = '';
bNeedClear = true;
break;
case "+":
case "-":
case "*":
case "/":
bNeedClear = true;
if (sNum1.length != 0) {
int.value = result(parseInt(sNum1), parseInt(int.value), sOpt);
}
sOpt = sHtml;
sNum1 = int.value;
break;
case 'c':
int.value = '0';
sNum1 = '';
sOpt = '';
break;
default: //数字
if (bNeedClear) {
int.value = parseInt(sHtml, 10);
bNeedClear = false;
} else {
int.value = parseInt(int.value + sHtml, 10);
}
break;
}
}
function result(num1, num2, sOpt) {
var res = 0;
switch (sOpt) {
case "+":
res = num1 + num2;
break;
case "-":
res = num1 - num2;
break;
case "*":
res = num1 * num2;
break;
case "/":
res = num1 / num2;
break;
default:
res = num2;
}
return res;
}
})();
</script>
</body>
</html>

JavaScript 简单计算器效果,这样的场景在实际项目中还是用的比较多的,关于JavaScript 简单计算器效果就介绍到这了。

JavaScript 简单计算器效果属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容