<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css" >
</head>
<body>
<div id="box">
<input type="text" id="result" value="0">
<table>
<tr>
<td><button>C</button></td>
<td><button>+/-</button></td>
<td><button>x</button></td>
<td><button>/</button></td>
</tr>
<tr>
<td><button>7</button></td>
<td><button>8</button></td>
<td><button>9</button></td>
<td><button>*</button></td>
</tr>
<tr>
<td><button>4</button></td>
<td><button>5</button></td>
<td><button>6</button></td>
<td><button>-</button></td>
</tr>
<tr>
<td><button>1</button></td>
<td><button>2</button></td>
<td><button>3</button></td>
<td><button>+</button></td>
</tr>
<tr>
<td colspan="2"><button class="zero">0</button></td>
<td><button>.</button></td>
<td><button>=</button></td>
</tr>
</table>
</div>
<script src="index.js"></script>
</body>
</html>
*{
margin: 0;
padding: 0;
font-weight: bold;
font-size: 16px;
}
body{
}
#box {
width: 500px;
height: 500px;
position: absolute;
left: calc(50% - 250px);
top: calc(50% - 250px);;
}
table {
margin: 20px auto;
}
button{
width: 80px;
height: 80px;
background-image: linear-gradient(160deg,#3498db,#8e44ad);
}
.zero{
width: 162px;
}
#result {
margin: auto;
display: block;
width: 320px;
height: 50px;
text-align: end;
border: none;
background-color: #fff;
}
const result =document.querySelector('#result')
const btn = document.getElementsByTagName('button')
let arr = []
let no_repeat = false
for(let i of btn){
i.addEventListener('click',function () {
if(!isNaN(this.innerHTML)) {
no_repeat = true
if(result.value !== "0") {
result.value += this.innerHTML
}else{
result.value = this.innerHTML
}
}else {
if(this.innerHTML === "." && result.value[result.value.length-1] !== ".") {
result.value += this.innerHTML
} else if(this.innerHTML === "+/-") {
if(result.value.indexOf('-') !== -1) {
result.value = result.value.replace(/-/,'')
}else {
if(result.value === "0") {
result.value = ""
}
if(result.value.startsWith('(')){
result.value = result.value.concat('-')
}else {
result.value = '-'.concat(result.value)
}
}
}else if (this.innerHTML === '(') {
if(result.value === "0") {
result.value = ""
}
result.value += '('
} else if (this.innerHTML === ')') {
if(result.value === "0") {
result.value = ""
}
result.value += ')'
} else {
switch (this.innerHTML) {
case "+":
noRepeat(this)
break
case "-":
noRepeat(this)
break
case "*":
noRepeat(this)
break
case "/":
noRepeat(this)
break
case "C":
result.value = 0
arr = []
break
case "x":
result.value = result.value.length === 1 ? "0" : result.value.substr(0,result.value.length -1)
break
case "=":
arr.push(result.value)
console.log(arr);
result.value = eval(arr.join(""))
arr = []
break
}
}
}
})
}
function noRepeat(str) {
if (!no_repeat) {
arr[arr.length-1] = str.innerHTML
} else {
arr.push(result.value)
arr.push(str.innerHTML)
}
result.value = "0";
no_repeat = false;
}