马黑PHP整站系统

计算器演算动画

位置: 首页 > 代码集锦[ 发布时间: 2024.1.4  作者: 马黑  阅读: 151 ]
开始

代码:


		
<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>

前一篇: js+css+svg花朵演示
下一篇: 烟消云散:CSS文本特效演示

发表评论:

       

评论列表 [1条]

#1 | 飞飞 于 2024-1-4 12:35 发布: 点开始就不知疲倦的算下去了,好勤快的。。

Copyright © 2023 All Right Reserved 马黑PHP文章管理整站系统v1.8
联系我们: gxblk@163.com