GoodCoder666的个人博客

在微信小程序中做自己的数字键盘

2020-01-31 · 4 min read
微信小程序

为什么要自制键盘?

我最近在开发一款微信小程序,现在需要用户输入一个数字。

使用系统键盘带来的不便

如果使用系统键盘,有以下几个问题:

  • 数字键太小,不方便;
  • 无法阻止用户输入不合法字符(如:“&”);
  • 小数点在一些手机上很难找到;
  • 用户需要点击输入框;
  • 无法控制按钮样式。

理想的自制键盘效果

123
456
789
.0提交
退格清空

怎样自制键盘?

每一行按钮捆绑成一个view:
WXML

<!--pages/a/a.wxml-->
<!--输入键盘-->
<!--五行,每行一个view-->
<view class='keyboard-row'>
  <button type='default' plain='true' class='one' data-key='1'  bindtap='tapKey'>1</button>
  <button type='default' plain='true' class='two' data-key='2' bindtap='tapKey'>2</button>
  <button type='default' plain='true' class='three' data-key='3' bindtap='tapKey'>3</button>
</view>
<view class='keyboard-row'>
  <button type='default' plain='true' class='four' data-key='4' bindtap='tapKey'>4</button>
  <button type='default' plain='true' class='five' data-key='5' bindtap='tapKey'>5</button>
  <button type='default' plain='true' class='six' data-key='6' bindtap='tapKey'>6</button>
</view>
<view class='keyboard-row'>
  <button type='default' plain='true' class='seven' data-key='7' bindtap='tapKey'>7</button>
  <button type='default' plain='true' class='eight' data-key='8' bindtap='tapKey'>8</button>
  <button type='default' plain='true' class='nine' data-key='9' bindtap='tapKey'>9</button>
</view>
<view class='keyboard-row'>
  <button type='default' plain='true' class='dot' data-key='.' bindtap='tapKey'>.</button>
  <button type='default' plain='true' class='zero' data-key='0' bindtap='tapKey'>0</button>
  <button type='default' plain='true' class='submit' bindtap='tapSubmit'>提交</button>
</view>
<!--clear&delete-->
<view class='keyboard-row'>
  <button type='default' plain='true' class='del'  bindtap='tapDel'>退格</button>
  <button type='default' plain='true' class='clear' bindtap='tapClear'>清除</button>
</view>

WXSS

/*pages/a/a.wxss*/
.keyboard-row {
  width: 100%;
  height: 35%;
  border-radius: 98rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

JS

// pages/a/a.js
Page({
  data: {
    num: 0,
    hasDot: false // 防止用户多次输入小数点
  },
  tapKey: function(evt) {
    var x = evt.currentTarget.dataset.key
    if(x == '.') {
      if(this.data.hasDot) return
      this.setData({
        hasDot: true
      })
    }
    this.setData({
      num: this.data.num == '0'? x: this.data.num + x
    })
  },
  tapSubmit: function() {
    // 用户已提交
    console.log('res =', this.data.num)
  },
  tapDel: function() {
    if(this.data.num == '0') return
    if(this.data.num[this.data.num.length - 1] == '.') this.setData({
      hasDot: false
    })
    this.setData({
      num: this.data.num.length == 1? '0': this.data.num.substring(0, this.data.num.length - 1)
    })
  },
  tapClear: function() {
    this.setData({
      num: '0',
      hasDot: false
    })
  }
})

键盘的效果

键盘效果图

CSDN:https://blog.csdn.net/write_1m_lines/article/details/104121630