微信小程序--简易计算器

一、项目概述

本文主要介绍了微信小程序的一个简易计算器的实现代码实例。

实现的功能有:

  1. 实现简单的加减乘除
  2. 删除
  3. 全部清空

小程序页面目录如下:

计算器页面如下:

二、WXML文件编写

首先我们对计算器页面进行设计,这里我们主要分为两部分,上部为结果显示,下部为按键部分分为操作数和操作符。

计算器分为五行四列,采用弹性显示结构,横向显示。布局通过样式表操作,

WXML代码如下:

<!-- pages/index/index.wxml -->

<view class='screen'>{{result}}</view>

<view class='test-bg'>
  <view class='btnGroup'>
    <view class='item green' bindtap='clickButton' id="{{C}}">AC</view>
    <view class='item green' bindtap='clickButton' id="{{back}}">←</view>
    <view class='item green' bindtap='clickButton' id="{{addSub}}">+/-</view>
    <view class='item green' bindtap='clickButton' id="{{div}}">÷</view>
  </view>

  <view class='btnGroup'>
    <view class='item blue' bindtap='clickButton' id="{{id7}}">7</view>
    <view class='item blue' bindtap='clickButton' id="{{id8}}">8</view>
    <view class='item blue' bindtap='clickButton' id="{{id9}}">9</view>
    <view class='item green' bindtap='clickButton' id="{{mut}}">×</view>
  </view>

  <view class='btnGroup'>
    <view class='item blue' bindtap='clickButton' id="{{id4}}">4</view>
    <view class='item blue' bindtap='clickButton' id="{{id5}}">5</view>
    <view class='item blue' bindtap='clickButton' id="{{id6}}">6</view>
    <view class='item green' bindtap='clickButton' id="{{sub}}">-</view>
  </view>

  <view class='btnGroup'>
    <view class='item blue' bindtap='clickButton' id="{{id1}}">1</view>
    <view class='item blue' bindtap='clickButton' id="{{id2}}">2</view>
    <view class='item blue' bindtap='clickButton' id="{{id3}}">3</view>
    <view class='item green' bindtap='clickButton' id="{{add}}">+</view>
  </view>

  <view class='btnGroup'>
    <view class='item blue' bindtap='clickButton' id="{{percent}}">%</view>
    <view class='item blue' bindtap='clickButton' id="{{id0}}">0</view>
    <view class='item blue' bindtap='clickButton' id="{{dot}}">.</view>
    <view class='item green' bindtap='clickButton' id="{{equ}}">=</view>
  </view>

</view>

三、WXSS文件编写

这里分两部分,计算结果展示区,计算按钮区。可见wxml文件注释。

下面为项目使用到的样式设计:

  1. display:flex 表示弹性布局,block块布局(后面接换行符)
    flex:1表示占满剩余空间(flex-grow,flex-shrink,flex-basis的简写)默认值为:0,1,auto, 不伸不缩。
  2. flex-direction:容器内元素的排列方向(默认横向排列)
    (1)flex-direction:row;沿水平主轴让元素从左向右排列。此时flex-basis相当于width。
    (2)flex-direction:colimn;沿垂直主轴从上到下排列。此时flex-basis相当于height
    (3)flex-direction:roe-reverse;沿水平主轴从右向左排列。
  3. bottom:bottom 属性规定元素的底部边缘。该属性定义了定位元素下外边距边界与其包含块下边界之间的偏移。
  4. text-align:text-align 属性规定元素中的文本的水平对齐方式。
  5. word-break:word-break 属性规定自动换行的处理方法。
  6. border-radius:border-radius 属性是一个简写属性,用于设置四个 border-*-radius 属性。该属性允许您为元素添加圆角边框!

WXSS代码如下:

/* pages/index/index.wxss */
page {
  width: 100%;
  height: 100%;
}

.test-bg {
  position: fixed;
  bottom: 0;
}

.screen {
  position: fixed;
  color: #000000;
  font-size: 30px;
  bottom: 780rpx;
  text-align: right;
  width: 730rpx;
  word-wrap: break-word;
}

.btnGroup {
  display: flex; /*弹性显示结构*/
  flex-direction: row;/*横向显示*/
}

.item {
  width: 192rpx;
  line-height: 148rpx;
  border-radius: 5%;
  text-align: center;
}

.green {
  /* 前景色 */
  color: #000000;
  border: solid 1rpx #ffffff;
  /* 背景色 */
  background: #CCFF99;
}

.blue {
  /* 前景色 */
  color: #000000;
  border: solid 1rpx #ffffff;
  /* 背景色 */
  background: #A7DFF1;
}

四、JS页面设计

JS页面是实现计算器计算的核心,它负责计算器计算的逻辑。在JS中将数据从前台传到后台是通过事件的方式(e),从后台传到前台用data的方式。

JS代码如下:

// pages/index/index.js
Page({
  data: {
    back: 'back',
    C: 'C',
    addSub: 'addSub',
    add: '+',
    sub: '-',
    mut: '×',
    div: '÷',
    equ: '=',
    percent: '%',
    dot: '.',
    id0: '0',
    id1: '1',
    id2: '2',
    id3: '3',
    id4: '4',
    id5: '5',
    id6: '6',
    id7: '7',
    id8: '8',
    id9: '9',
    result: '0',
    valiBackOfArray: ['+', '-', '×', '÷', '.'],
    completeCalculate: false
  },
  // 计算结果
  calculate: function (str) {
    // 判断是不是有负数
    var isNagativeNum = false;
    if (str.charAt(0) == '-') {
      str = str.replace('-', '').replace('(', '').replace(')', '');
      isNagativeNum = true;
    }
    // 对字符串解析并运算
    var addArray = str.split('+');
    var sum = 0.0;
    for (var i = 0; i < addArray.length; i++) {
      if (addArray[i].indexOf('-') == -1) {
        if (addArray[i].indexOf('×') != -1 || addArray[i].indexOf('÷') != -1)
          sum += this.calculateMutDiv(addArray[i]);
        else sum += Number(addArray[i]);
      }
      else {
        var subArray = addArray[i].split('-');
        var subSum = 0;
        if (subArray[0].indexOf('×') != -1 || subArray[0].indexOf('÷') != -1) subSum = this.calculateMutDiv(subArray[0]);
        else subSum = Number(subArray[0]);
        for (var j = 1; j < subArray.length; j++) {
          if (subArray[i].indexOf('×') != -1 || subArray[i].indexOf('÷') != -1)
            subSum -= this.calculateMutDiv(subArray[j]);
          else subSum -= Number(subArray[j]);
        }
        sum += subSum;
      }
    }
    if (isNagativeNum) return (-sum).toString();
    else return sum.toString();
  },
  // 分块乘除运算
  calculateMutDiv: function (str) {
    var addArray = str.split('×');
    var sum = 1.0;
    for (var i = 0; i < addArray.length; i++) {
      if (addArray[i].indexOf('÷') == -1) {
        sum *= Number(addArray[i]);
      }
      else {
        var subArray = addArray[i].split('÷');
        var subSum = Number(subArray[0]);
        for (var j = 1; j < subArray.length; j++) {
          subSum /= Number(subArray[j]);
        }
        sum *= subSum;
      }
    }
    return sum;
  },
  // 是否以运算符结尾
  isOperatorEnd: function (str) {
    for (var i = 0; i < this.data.valiBackOfArray.length; i++) {
      if (str.charAt(str.length - 1) == this.data.valiBackOfArray[i]) return true;
    }
    return false;
  },
  clickButton: function (event) {
    if (this.data.result == 0) {
      if (event.target.id == 'back' || event.target.id == 'C' || event.target.id == 'addSub' || event.target.id == '%' || event.target.id == '+' || event.target.id == '-' || event.target.id == '×' || event.target.id == '÷' || event.target.id == '=') return;
      this.setData({
        result: event.target.id
      });
    }
    else if (event.target.id == 'back') {
      this.setData({
        result: this.data.result.length == 1 ? '0' : this.data.result.substring(0, this.data.result.length - 1)
      });
    }
    else if (event.target.id == 'C') {
      this.setData({
        result: '0'
      });
    }
    else if (event.target.id == 'addSub') {
      var r = this.data.result;
      if (this.isOperatorEnd(r)) return;
      if (r.charAt(0) == '-') this.setData({ result: r.replace('-', '').replace('(', '').replace(')', '') });
      else this.setData({
        result: '-(' + r + ')'
      });
    }
    else if (event.target.id == '%') {
    }
    else if (event.target.id == '=') {
      if (this.isOperatorEnd(this.data.result)) return;
      this.setData({
        result: this.calculate(this.data.result)
      });
      this.setData({
        completeCalculate: true
      });
    }
    else {
      if (this.isOperatorEnd(this.data.result) && this.isOperatorEnd(event.target.id)) return;
      // 如果计算结果有小数点,直到输入运算符前不能再输入小数点
      if (this.data.completeCalculate && this.data.result.indexOf('.') != -1 && event.target.id == '.') return;
      for (var i = 0; i < this.data.valiBackOfArray.length - 1; i++) {
        if (this.data.valiBackOfArray[i] == event.target.id) {
          this.setData({
            completeCalculate: false
          });
          break;
        }
      }
      this.setData({
        result: this.data.result + event.target.id
      });
    }
  }
})

五、实现效果展示

完整项目地址:https://github.com/xianlong-H/WeChat_calculator

  • 41
    点赞
  • 215
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Huang_xianlong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值