这个很简单也没什么技术含量,主要用到的就是js的eval();eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码。我的思路主要是点击输入一个表达式,然后eval这个string,try catch一下;我写的这个兼容性不好,主要是事件对象的获取,在ie中获取不了(window.even获取)我这个直接写了。eval很强大
慢慢学吧。`
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
.wra {
width: 300px;
height: auto;
overflow: hidden;
border: 1px solid #D9E400;
background: #D9E4F1;
}
.xian {
height: 80px;
background: #ffffff;
font-size: 30px;
line-height: 80px;
}
.num {
width: 45px;
height: 45px;
float: left;
margin: 10px;
line-height: 45px;
text-align: center;
}
.btnli {
width: 300px;
float: left;
display: flex;
justify-content: center;
flex-wrap: wrap;
}
</style>
<body>
<div class="wra">
<div class="xian" id="xian"></div>
<div class="btnli" id="btnli" draggable="false">
<input class="num" type="button" value="1"/>
<input class="num" type="button" value="2"/>
<input class="num" type="button" value="3"/>
<input class="num" type="button" value="+"/>
<input class="num" type="button" value="4"/>
<input class="num" type="button" value="5"/>
<input class="num" type="button" value="6"/>
<input class="num" type="button" value="-"/>
<input class="num" type="button" value="7"/>
<input class="num" type="button" value="8"/>
<input class="num" type="button" value="9"/>
<input class="num" type="button" value="*"/>
<input class="num" type="button" value="0"/>
<input class="num" type="button" value="."/>
<input class="num" type="button" value="="/>
<input class="num" type="button" value="/"/>
</div>
</div>
</body>
<script type="text/javascript">
var xian = document.getElementById('xian');
var nums = document.getElementById('btnli').getElementsByTagName('input');
for (var i = 0; i < nums.length; i++) {
if (i == 14) {
nums[14].onclick = function (even) {
try {
xian.innerHTML = eval(xian.innerHTML);
} catch (err) {
alert('error')
}
}
} else {
nums[i].onclick = function (even) {
xian.innerHTML += even.target.value;
}
}
}
document.onkeydown = function (even) {
if (xian.innerHTML.length != 0 && even.keyCode == 8) {
xian.innerHTML = xian.innerHTML.slice(0, xian.innerHTML.length - 1);
}
}
</script>
</html>`