App-idea简单项目三
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./index.css" type="text/css" />
<title>Calculator</title>
</head>
<body>
<div>
<p style="color: #fff">My Calculator</p>
<div>
<div id="resultDisplay"></div>
<div>
<div>
<button class="clearButton" onclick="handleClick(this)">CE</button>
<button class="clearButton" onclick="handleClick(this)">C</button>
<button class="operatorButton" onclick="handleClick(this)">
%
</button>
<button class="operatorButton" onclick="handleClick(this)">
/
</button>
</div>
<div>
<button class="button" onclick="handleClick(this)">7</button>
<button class="button" onclick="handleClick(this)">8</button>
<button class="button" onclick="handleClick(this)">9</button>
<button class="operatorButton" onclick="handleClick(this)">
X
</button>
</div>
<div>
<button class="button" onclick="handleClick(this)">4</button>
<button class="button" onclick="handleClick(this)">5</button>
<button class="button" onclick="handleClick(this)">6</button>
<button class="operatorButton" onclick="handleClick(this)">
-
</button>
</div>
<div>
<button class="button" onclick="handleClick(this)">1</button>
<button class="button" onclick="handleClick(this)">2</button>
<button class="button" onclick="handleClick(this)">3</button>
<button class="operatorButton" onclick="handleClick(this)">
+
</button>
</div>
<div>
<button
id="number0Button"
class="button"
onclick="handleClick(this)"
>
0
</button>
<button class="button" onclick="handleClick(this)">.</button>
<button class="operatorButton" onclick="handleClick(this)">
=
</button>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="./index.js" defer="defer"></script>
</html>
CSS:
:root{
text-align: center;
background-color: #808080;
}
button{
width:80px;
height: 40px;
margin: 2px 2px;
border: none;
}
#number0Button{
width:169px;
height: 40px;
}
.operatorButton{
background-color: #725e82;
}
#resultDisplay{
width:346px;
height: 40px;
background-color: #fff;
margin:2px auto;
color: black;
}
.clearButton{
background-color:#e0eee8;
}
JS:
var calFormula = '';
function handleClick(obj) {
var textStr = obj.innerText;
var str = '';
if (textStr == '=') {
var result = eval(calFormula);
str = textStr;
} else {
str = textStr;
}
if (textStr == 'C') {
str = '';
calFormula = calFormula.substring(0, calFormula.length - 1);
}
if (textStr == 'CE') {
str = '';
calFormula = '';
}
calFormula += str;
var displayDiv = document.getElementById("resultDisplay");
displayDiv.innerText = calFormula;
if (result) {
displayDiv.innerText = calFormula + result;
calFormula = '';
}
}
最终实现效果:
Tips:
1.onClick()处理传入this指针即为点击的标签。通过innerText获取到点击的按钮的值
2.eval()计算字符串里的公式
3.JS 字符串方法巩固
4.由于赶时间还未完成用户输入控制。