JavaScript - Calculator.html

创建时间:
2018-07-05 12:06
最近更新:
2018-10-28 00:31

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>@ViewBag.Title</title>
<link rel="icon" href="http://www.baidu.com/favicon.ico" />
<link rel="stylesheet" href="http://apps.bdimg.com/libs/bootstrap/3.3.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="http://apps.bdimg.com/libs/bootstrap/3.3.0/css/bootstrap-theme.min.css" />
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="http://apps.bdimg.com/libs/html5shiv/3.7/html5shiv.min.js"></script>
<script src="http://apps.bdimg.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<style>
input{
width: 99%;
font-size: 3em;
margin: auto;
display: block;
}
body>div{
text-align: center;
}
span{
border: 1px solid #aaa;
font-size: 2em;
width: 2em;
line-height: 2em;
margin: 3px;
display: inline-block;
}
</style>
</head>
<body>
<input />
<div>
<div>
<span>C</span>
<span>←</span>
</div>
<div>
<span>7</span>
<span>8</span>
<span>9</span>
<span>/</span>
</div>
<div>
<span>4</span>
<span>5</span>
<span>6</span>
<span>*</span>
</div>
<div>
<span>1</span>
<span>2</span>
<span>3</span>
<span>-</span>
</div>
<div>
<span>0</span>
<span>.</span>
<span>=</span>
<span>+</span>
</div>
</div>

<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://apps.bdimg.com/libs/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script>
var jIpt = $('input');
jIpt.focus(function(){
this.select();
});
$(document).on('click', 'span', function(){
var key = $(this).html();
if(key === 'C'){
jIpt.val('');
return;
}
var ipt = jIpt.val();
if(key === '←'){
ipt = ipt.slice(0, -1);
jIpt.val(ipt);
return;
}
ipt += key;
jIpt.val(ipt);
if(key === '='){
var output = Calculate();
jIpt.val(output);
}
});
function Calculate(){
var ipt = jIpt.val();
try{
var result = eval(ipt.replace('=', ''));
}catch(e){
return '';
}
var output = ipt + result;
return output;
}
</script>
</body>
</html>