首页 > 代码库 > js实现简单计算器

js实现简单计算器

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
.calculate{
width: 360px;
height: 600px;
margin: 50px auto;
background-color: silver;
border-top: 2px solid black;
border-left: 2px solid black;
}
.calculate .show{
width: 360px;
height: 200px;
background-color: black;
color: white;
}
.calculate .symbol{
width: 360px;
height: 400px;
background-color: khaki;
}
.calculate .symbol ul{
list-style: none;
}
.calculate .symbol ul li{
width: 68px;
height: 78px;
padding-left: 20px;
border-bottom: 2px solid black;
border-right: 2px solid black;
float: left;
font-size: 40px;
}
.calculate .symbol ul .zero{
border-right: 2px solid khaki;
}
</style>
</head>
<body>
<div class="calculate">
<div class="show" id="show"></div>
<div class="symbol">
<ul id="button">
<li>AC</li>
<li>+/-</li>
<li>%</li>
<li>÷</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>×</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>-</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>+</li>
<li class="zero">0</li>
<li></li>
<li>.</li>
<li>=</li>
</ul>
</div>
</div>
<script>
var first = null,second = null, getNum = 0;
var fuhao = null,flag = true;
var buttons = document.getElementById("button");
var show = document.getElementById("show");
var lis = buttons.getElementsByTagName("li");
for(var i = 3; i < 16; i++){
lis[i].index = i;
if( i ==3 || i == 7 || i ==11 || i == 15){
lis[i].onclick = function () {
fuhao = this.innerHTML;
flag = false;
}
}else{
lis[i].onclick = function () {
if(flag){
first = lis[this.index].innerHTML;
}else{
second = lis[this.index].innerHTML;
}
show.innerHTML = lis[this.index].innerHTML;
}
}
}
lis[19].onclick = function () {
first = parseFloat(first);
second = parseFloat(second);
if(fuhao == "÷"){
getNum = first/second;
}
if(fuhao == "×"){
getNum = first*second;
}
if(fuhao == "-"){
getNum = first - second;
}
if(fuhao == "+"){
console.log(first);
console.log(second);
getNum = first + second;
}
first = getNum;
flag = true;
show.innerHTML = getNum;
}
</script>
</body>
</html>

js实现简单计算器