只能实现简单的加减乘除
代码逻辑简单易懂,效果图如下,希望大佬来指正更好的写法和功能
<!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" />
<title>计算器</title>
<style>
* {
margin: 0;
padding: 0;
}
.container {
background-color: red;
height: 400px;
width: 600px;
position: absolute;
top: calc(50% - 200px);
left: calc(50% - 300px);
}
.header {
height: 100px;
background-color: #fcfdff;
font-size: 32px;
display: flex;
justify-content: flex-end;
align-items: flex-end;
}
.content {
height: 300px;
}
ul {
height: 60px;
background-color: white;
display: flex;
}
.content > ul:first-child {
color: red;
background-color: #f9f9f9;
}
.content > ul:first-child > li:last-child {
color: black !important;
}
.content > ul > li:last-child {
color: red;
background-color: #f9f9f9;
}
.color_red {
color: red;
}
li {
list-style: none;
width: 150px;
text-align: center;
line-height: 60px;
font-size: 30px;
cursor: pointer;
border: 1px solid #ebebeb;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<p id="message">0</p>
</div>
<div class="content">
<ul>
<li>(</li>
<li>)</li>
<li>%</li>
<li id="clear">C</li>
</ul>
<ul>
<li>7</li>
<li>8</li>
<li>9</li>
<li>/</li>
</ul>
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
<li>*</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>-</li>
</ul>
<ul>
<li>0</li>
<li class="color_red">.</li>
<li class="color_red" id="getResult">=</li>
<li>+</li>
</ul>
</div>
</div>
<script>
let result = document.getElementById("message");
let uls = document.getElementsByTagName("ul");
for (let i = 0; i < uls.length; i++) {
let ulBtn = uls[i].children;
for (let j = 0; j < ulBtn.length; j++) {
ulBtn[j].onclick = function () {
if (result.innerHTML.length === 1 && result.innerHTML == "0") {
result.innerHTML = "";
result.innerHTML += this.innerHTML;
} else {
result.innerHTML += this.innerHTML;
}
};
}
}
let clear = document.getElementById("clear");
clear.onclick = function () {
result.innerHTML = "0";
};
let getResult = document.getElementById("getResult");
getResult.onclick = function () {
result.innerHTML = eval(...result.innerHTML);
};
</script>
</body>
</html>