<style>
#wrap { margin: 30px auto; position: relative; padding: 10px; border: 1px solid tan; border-radius: 10px; background: #eee; box-shadow: 2px 2px 6px gray; font-size: 16px; }
#wrap::before { position: absolute; left: 6px; top: 4px; content: '计算器'; }
#calcMsg { margin: 26px 0; padding: 4px; height: 20px; background: white; font: normal 14px/20px sans-serif; overflow: hidden; }
#cBox { max-width: 126px; display: flex; gap: 2px; flex-wrap: wrap; }
#cBox span { display: grid; place-items: center; width: 30px; height: 30px; background: lightblue; border-radius: 50%; }
#okey { margin: 10px 0 0 0; padding: 2px; text-align: center; cursor: pointer; border-radius: 10px; background: lightblue; }
#okey:hover { color: red; }
</style>
<div id="wrap">
<div id="calcMsg"></div>
<div id="cBox"></div>
<div id="okey">开始</div>
</div>
<script>
let charIdx = 0, equation = '', btns = [], timer;
let spans = ['0','1','2','3','4','5','6','7','8','9','.','=','+','-','*','/'];
spans.forEach((span,key) => {
let sp = document.createElement('span');
sp.innerText = span;
cBox.appendChild(sp);
btns.push(sp);
});
let mkequ = () => {
let operators = ['+','-','*','/'];
var n1 = Math.floor(Math.random() * 1000),
n2 = Math.floor(Math.random() * 1000),
operate = operators[Math.floor(Math.random() * 4)];
let res = parseFloat(eval(`${n1}${operate}${n2}`));
if(res.toString().indexOf('.') != -1) res = res.toFixed(2);
return `${n1}${operate}${n2}=${res}`;
};
equation = mkequ();
let update = () => {
let charNow = equation.charAt(charIdx);
calcMsg.innerText += charNow;
for(let j = 0; j < btns.length; j ++) {
if(btns[j].innerText === charNow) btns[j].style.background = 'pink';
}
charIdx ++;
if(charIdx > equation.length) {
calcMsg.innerText = '';
charIdx = 0;
equation = mkequ();
btns.forEach(elm => elm.style.background = 'lightblue');
}
timer = setTimeout(update,300);
};
okey.onclick = () => {
timer = timer ? clearTimeout(timer) : setTimeout(update,500);
okey.innerText = timer ? '暂停' : '开始';
};
</script>