通过实际操作,基本熟悉计算器代码,并且可以自行写出来.
css代码
/* 计算器css */
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background-color: #eee;
}
.calculator{
min-width: 360px;
max-width: 460px;
/* border: 1px solid ; */
display: grid;
gap: 10px;
grid-template-rows: 50px 1fr;
margin: 20px auto;
padding: 10px;
box-shadow: 2px 2px 2px #333;
border-radius: 5px;
background-color: #666;
}
.calculator .result{
background-color: #cecece;
text-align: right;
font-size: 32px;
border: none;
outline: none;
padding: 5px;
font-weight: bolder;
box-shadow: 2px 2px 2px #333 inset;
border-radius: 5px;
}
.calculator .btn{
display: grid;
grid-template-columns: repeat(4,1fr);
gap:10px;
grid-auto-rows: 60px;
}
.calculator .btn button:nth-child(-n+4)
{
background-color: #fff;
}
.calculator .btn button{
border-radius: 8px;
background-color: #cecece;
box-shadow: 2px 2px 2px #000 ;
font-size: 32px;
font-weight: bolder;
}
.calculator .btn button:hover{
cursor: pointer;
color: #000;
/* 透明度 */
opacity: 0.7;
transition: 0.3s;
}
.calculator .btn button:nth-child(-n+4):hover{
color: #000;
}
js代码
function calculator(ev){
// 获取到结果区
let result = document.querySelector('.result')
//获取到时间触发者的标签是否是button
// console.log(ev.target.tagName);
// console.log(ev);
//获取到事件触发者target的标签tagName不等于BUTTON 直接返回false
if (ev.target.tagName != 'BUTTON') return false
//获取标签的值
let content = ev.target.textContent
// console.log(content);
switch(content){
//元素的值是AC 直接清零
case 'AC' :
result.value = 0
break
// CE 是退格
case 'CE':
if(result.value.length==1 || result.value=='错误')
{
result.value = 0
}else{
//退格:(0,-1)表示从起始值到最后一个值,获取字符串的子串,忽略最后一个字符
result.value = result.value.slice(0,-1)
}
break
//通过eval():计算字符串
case '=':
// toFix()必须是number数字类型
let tmpResult = 0
// console.log(typeof tmpResult);
try{
//因为eval只能识别*,所以要把x替换成*
result.value = result.value.replace('x','*')
tmpResult = eval(result.value)
if(tmpResult.toString().includes('.'))
tmpResult = tmpResult.toFixed(5)
//小数部分多余的0去掉
tmpResult = parseFloat(tmpResult)
//如果除0出现无穷大Infinity,提示错误
if(tmpResult == Infinity)
tmpResult = '错误'
result.value = tmpResult
}
catch{
result.value = '错误'
}
break
default:
// if(result.value=='+' || result.value=='-'|| result.value=='x' || result.value=='/')
if(result.value == 0 || result.value=='错误' || result.value=='+' || result.value=='-'|| result.value=='x' || result.value=='/')
result.value=''
//默认显示输入的内容
result.value += content
}
}
其中处理除零错误
//如果除0出现无穷大Infinity,提示错误
if(tmpResult == Infinity)
tmpResult = '错误'
处理操作符位于表达式首位的错误
if(result.value == 0 || result.value=='错误' || result.value=='+' || result.value=='-'|| result.value=='x' || result.value=='/')
result.value=''