<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
</head>
<title>计算器</title>
<style>
#all {
width: 300px;
height: 500px;
background: #ccc;
margin: auto;
}
td {
width: 60px;
height: 60px;
text-align: center;
}
#jp {
width: 270px;
height: 80px;
margin: 0 auto;
position: relative;
}
#jg {
width: 270px;
height: 70px;
background: #ffffff;
position: absolute;
top: 10px;
}
</style>
<body>
<div id="all">
<div id="jp">
<div id="jg"></div>
</div>
<table width="90%" height="300" border="1" align="center" cellspacing="10">
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
<td>+</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
<td>-</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>*</td>
</tr>
<tr>
<td>0</td>
<td>.</td>
<td id="dengyu">=</td>
<td>/</td>
</tr>
<tr>
<td id="cle">清空</td>
<td id="tg">退格</td>
</tr>
</table>
</div>
<script>
var oTd = document.querySelectorAll('td')
var oDiv = document.querySelector('#jg')
// console.log(oDiv)
console.log(oTd)
var str = ''
oTd.forEach(function(item,index){
// console.log(item)
item.addEventListener('click',function(){
// console.log(item.innerText)
if(item.innerText==='='){
oDiv.innerText = eval(str) //计算字符串类型的表达式 eval('5*4')
str = '' //计算后清空,方便下一次输入
}
else if(item.innerText==='清空'){
str = ''
oDiv.innerText = '0'
}
else if(item.innerText==='退格'){
str = str.substr(0,str.length-1) //删除最后一个字符
oDiv.innerText = str
}
// 其余字符直接拼接就行
else{
str += item.innerText
oDiv.innerText = str
}
})
})
</script>
</body>
</html>
12-24
926