微信小程序實現計算器小功能

微信小程序現在越來越火爆瞭,我也看到很多在校大學生都在自學瞭,那些專門從事APP開發,網頁開發的工作者更是看到瞭小程序的前景,在小程序領域也摻上一腳,本人也是自學小程序的,初期跟很多人一樣,遇到一些不懂的想問問別人,到貼吧去,一大堆廣告,根本沒人幫忙解決問題。

今天教一些剛入門的同學做一款計算器,如果C語言是編程的最佳入門語言,那計算器應該算得上是小程序的入門demo瞭,希望剛入門的同學們認真品味下面的代碼,從wxml到js,再到wxss(頁面的佈局),每個代碼都要弄懂他的意思

廢話不多說,先上效果圖,這是我入門時候自己做的一款計算器,很簡單,邏輯也很單一,隻是我們身邊最常見的計算器的邏輯,我覺得從這個demo我更深刻學習到瞭wxss頁面的佈局知識

代碼附上:

app.json

 {
  "pages":[
    "pages/index/index",
    "pages/logs/logs"
  ],
  "window":
  {
  "navigationBarBackgroundColor": "#000000",
  "navigationBarTextStyle": "white", 
  "navigationBarTitleText": "智能計算器"
  },
 "tabBar": {   //補充說一下,我這個tabBar是用來設置底部tab的
   "color":"#ff69b4",
   "selectedColor":"#0000ff",
   "backgroundColor":"#ffff00",
  "list": [
    {
      "pagePath": "pages/index/index",
      "text": "計 算 機"
    },
    {
      "pagePath": "pages/logs/logs",
      "text": "日志"
    },
    {
      "pagePath":"pages/logs/logs",
      "text":"回傢"
    }
  ]
}
}

/*app.wxss/*

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 200rpx 0;
  box-sizing: border-box;
} 

**其中一些組件不認識的話, 建議到微信小程序官網多看幾遍

index.wxml:

<template name="calculator-key">
  <button hover-start-time="{{5}}" hover-stay-time="{{100}}" hover-class="calculator-key-hover" data-key="{{className}}" class="calculator-key {{className}}">{{display}}</button>
</template>

<view class="calculator">
  <view class="calculator-display">
    <view class="calculator-display-text">{{displayValue}}</view>
  </view>
  <view class="calculator-keypad">
    <view class="input-keys">
      <view class="function-keys" catchtap="onTapFunction">
        <template is="calculator-key" data="{{className: 'key-clear', display: clearDisplay ? 'C' : 'C'}}"/>
        <template is="calculator-key" data="{{className: 'key-sign', display: '+/-'}}"/>
        <template is="calculator-key" data="{{className: 'key-percent', display: '%'}}"/>
   </view>
      <view class="digit-keys" catchtap="onTapDigit">
        <template is="calculator-key" data="{{className: 'key-0', display: '0'}}"/>
        <template is="calculator-key" data="{{className: 'key-dot', display: '●'}}"/>
        <template is="calculator-key" data="{{className: 'key-1', display: '1'}}"/>
        <template is="calculator-key" data="{{className: 'key-2', display: '2'}}"/>
        <template is="calculator-key" data="{{className: 'key-3', display: '3'}}"/>
        <template is="calculator-key" data="{{className: 'key-4', display: '4'}}"/>
        <template is="calculator-key" data="{{className: 'key-5', display: '5'}}"/>
        <template is="calculator-key" data="{{className: 'key-6', display: '6'}}"/>
        <template is="calculator-key" data="{{className: 'key-7', display: '7'}}"/>
        <template is="calculator-key" data="{{className: 'key-8', display: '8'}}"/>
        <template is="calculator-key" data="{{className: 'key-9', display: '9'}}"/>
      </view>
    </view>
    <view class="operator-keys" catchtap="onTapOperator">
        <template is="calculator-key" data="{{className: 'key-divide', display: '÷'}}"/>
        <template is="calculator-key" data="{{className: 'key-multiply', display: '×'}}"/>
        <template is="calculator-key" data="{{className: 'key-subtract', display: '−'}}"/>
        <template is="calculator-key" data="{{className: 'key-add', display: '+'}}"/>
        <template is="calculator-key" data="{{className: 'key-equals', display: '='}}"/>
    </view>
  </view>
</view>

index.js:

Page({
  data: {
    value: null, // 上次計算後的結果,null表示沒有上次計算的結果
    displayValue: '0', // 顯示數值
    operator: null, // 上次計算符號,null表示沒有未完成的計算
    waitingForOperand: false // 前一按鍵是否為計算符號
  },

  onLoad: function (options) {
    this.calculatorOperations = {
      'key-divide': (prevValue, nextValue) => prevValue / nextValue,
      'key-multiply': (prevValue, nextValue) => prevValue * nextValue,
      'key-add': (prevValue, nextValue) => prevValue + nextValue,
      'key-subtract': (prevValue, nextValue) => prevValue - nextValue,
      'key-equals': (prevValue, nextValue) => nextValue
    }
  },

  /* AC操作,一下回到解放前 */
  clearAll() {
    this.setData({
      value: null,
      displayValue: '0',
      operator: null,
      waitingForOperand: false
    })
  },

  /* 僅清空當前顯示的輸入值 */
  clearDisplay() {
    this.setData({
      displayValue: '0'
    })
  },

  onTapFunction: function (event) {
    const key = event.target.dataset.key;

    switch (key) {
      case 'key-clear':
        if (this.data.displayValue !== '0') {
          this.clearDisplay();
        } else {
          this.clearAll();
        }

        break;

      case 'key-sign':
        var newValue = parseFloat(this.data.displayValue) * -1

        this.setData({
          displayValue: String(newValue)
        })

        break;

      case 'key-percent':
        const fixedDigits = this.data.displayValue.replace(/^-?\d*\.?/, '')
        var newValue = parseFloat(this.data.displayValue) / 100

        this.setData({
          displayValue: String(newValue.toFixed(fixedDigits.length + 2))
        });

        break;

      default:
        break;
    }
  },

  onTapOperator: function (event) {
    const nextOperator = event.target.dataset.key;
    const inputValue = parseFloat(this.data.displayValue);

    if (this.data.value == null) {
      this.setData({
        value: inputValue
      });
    } else if (this.data.operator) {
      const currentValue = this.data.value || 0;
      const newValue = this.calculatorOperations[this.data.operator](currentValue, inputValue);

      this.setData({
        value: newValue,
        displayValue: String(newValue)
      });
    }

    this.setData({
      waitingForOperand: true,
      operator: nextOperator
    });
  },

  onTapDigit: function (event) {
    const key = event.target.dataset.key; // 根據data-key標記按鍵

    if (key == 'key-dot') {
      // 按下點號
      if (!(/\./).test(this.data.displayValue)) {
        this.setData({
          displayValue: this.data.displayValue + '.',
          waitingForOperand: false
        })
      }
    } else {
      // 按下數字鍵
      const digit = key[key.length - 1];

      if (this.data.waitingForOperand) {
        this.setData({
          displayValue: String(digit),
          waitingForOperand: false
        })
      } else {
        this.setData({
          displayValue: this.data.displayValue === '0' ? String(digit) : this.data.displayValue + digit
        })
      }
    }
  }
})

index.wxss:

page {
  height:100%;
}

.calculator {
  width: 100%;
  height: 100vh;
  border:solid 1px;
  background: rgb(238, 5, 5);
  position: relative;
  box-shadow: 0px 0px 20px 0px rgb(211, 41, 41);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.calculator-display {     /*顯示器背景顏色*/
  background: #2c2a2c;
  flex: 1;
}

/*TODO:解決文本垂直居中問題,顯示器數字顏色*/
.calculator-display-text {
  padding: 0 30px;
  font-size: 3em;
  color: rgb(245, 245, 248);
  text-align: right;
}

.calculator-keypad {
  display: flex;

}

.calculator .function-keys {
  display: flex;
  color:rgb(245, 13, 13);

}

.calculator .digit-keys {
  background: #0808f7;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap-reverse;
}

.calculator-key-hover {   /*按鈕按下以後的顏色*/
  box-shadow: inset 0px 0px 25vw 0px hsla(71, 90%, 48%, 0.898);
}



.calculator-key {
background-color:aqua;

  display: block;
  width: 25vw;
  height: 25vw;
  line-height: 25vw;
  border-top: 1px solid rgb(6, 245, 78);
  border-right: 1px solid rgb(19, 241, 12);
  text-align: center;
  box-sizing: border-box;
}

.calculator .function-keys .calculator-key {
  font-size: 2em;

}

.calculator .digit-keys .calculator-key {
  font-size: 3em;
}

.calculator .digit-keys .key-0 {
  width: 50vw;
  text-align: left;
  padding-left: 9vw;
}

.calculator .digit-keys .key-dot {
  padding-top: 1em;
  font-size: 0.75em;
}

.calculator .operator-keys .calculator-key {
  color: rgb(248, 165, 10);
  border-right: 0;
  font-size: 3em;
}

.calculator .function-keys {
  background: linear-gradient(to bottom, rgb(6, 6, 240) 0%, rgb(52, 5, 240) 100%);
}

.calculator .operator-keys {
  background:  linear-gradient(to bottom, rgba(252,156,23,1) 0%, rgba(247,126,27,1) 100%);
}

.input-keys {
  width: 100%;
}

.operator-keys {
  width: 100%;
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: