[js] 小案例---简易版计算器

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
</head>
<title>计算器</title>
<style>
  #all {
    width: 300px;
    height: 500px;
    background: #ccc;
    margin: auto;
  }

  td {
    width: 60px;
    height: 60px;
    text-align: center;
  }

  #jp {
    width: 270px;
    height: 80px;
    margin: 0 auto;
    position: relative;
  }

  #jg {
    width: 270px;
    height: 70px;
    background: #ffffff;
    position: absolute;
    top: 10px;
  }
</style>

<body>
  <div id="all">
    <div id="jp">
      <div id="jg"></div>
    </div>
    <table width="90%" height="300" border="1" align="center" cellspacing="10">
      <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>.</td>
        <td id="dengyu">=</td>
        <td>/</td>
      </tr>
      <tr>
        <td id="cle">清空</td>
        <td id="tg">退格</td>
      </tr>
    </table>
  </div>

  <script>
    var oTd = document.querySelectorAll('td')
    var oDiv = document.querySelector('#jg')
    // console.log(oDiv)
    console.log(oTd)
    
    var str = ''
    oTd.forEach(function(item,index){
      // console.log(item)
      item.addEventListener('click',function(){
        // console.log(item.innerText)
        if(item.innerText==='='){
          oDiv.innerText = eval(str)   //计算字符串类型的表达式  eval('5*4')
          str = ''    //计算后清空,方便下一次输入
        }
        else if(item.innerText==='清空'){
          str = ''
          oDiv.innerText = '0'
        }
        else if(item.innerText==='退格'){
          str = str.substr(0,str.length-1)   //删除最后一个字符
          oDiv.innerText = str
        }
        // 其余字符直接拼接就行
        else{
          str += item.innerText
          oDiv.innerText = str

        }
      })
    })

  </script>
</body>

</html>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值