码迷,mamicode.com
首页 > Web开发 > 详细

js实现简单计算器

时间:2016-10-12 14:16:39      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

<!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实现简单计算器

标签:

原文地址:http://www.cnblogs.com/zhangxyjack/p/5952355.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!