用html+css+js完成计算器的基本功能,代码如下:
HTML代码
<div id="four"> <div class="evaluator"><div class="input"><input type="text"></div><table><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>c</td><td>=</td><td>/</td></tr></table></div></div>
CSS代码
#four .evaluator{border: 2px gray solid;width: 240px;
}
#four input{width: 200px;padding: 5px;}
#four .input{width: 200px;margin: 10px auto;
}
#four table{width: 240px;border-collapse:separate;border-spacing:15px 15px;
}
#four td{padding: 5px 15px;border: 1px black solid;
}
#four td:active{background-color: gray;
}
JS代码
const input = document.querySelector("#four input");
const tdList = document.querySelectorAll("#four td");
let evalstr = "";
console.log(tdList);
for(let i = 0;i < tdList.length;i++){tdList[i].addEventListener("click",()=>{if(tdList[i].innerText == "c"){evalstr = "";}else if(tdList[i].innerText == "="){if(evalstr.length>0&&Object.is(Number(evalstr.charAt(evalstr.length-1)),NaN)){console.log(evalstr.charAt(evalstr.length-1));alert("请不要进行错误输入");evalstr = "";}else{evalstr = new String(eval(evalstr));}}else if((evalstr.length==0||evalstr.length==1)&&(tdList[i].innerText == "+"||tdList[i].innerText == "*"||tdList[i].innerText == "/")&&Object.is(Number(evalstr.charAt(0),NaN))){}else if((evalstr.length==0&&Object.is(Number(tdList[i].innerText),NaN))||(evalstr.length!=0&&Object.is(Number(evalstr.charAt(evalstr.length-1)),NaN)&&Object.is(Number(tdList[i].innerText),NaN))){evalstr = evalstr.substring(0,evalstr.length-1) +tdList[i].innerText;}else{evalstr += tdList[i].innerText;}if(evalstr == "Infinity"){alert("请不要进行错误输入");evalstr = "";}input.value = evalstr;});
};
效果图: