小程序開發日志-4、6位驗證碼輸入框制作


下面來為大家講講在小程序上怎么用做一組6位驗證碼輸入框。

先看看效果圖:

 

 

 

要做到上面的效果並不難,先說說思路:

首先我們需要做兩排輸入框,一排用於獲取焦點,一排用於填充。

 

 

 

 從上面的抽象的圖畫可以看出,單點擊一排輸入框的時候,也就是獲取到了焦點,輸入數字,將輸入的內容分別拆分成一個個字符填充到第二排輸入框中。

接下來要做的是將第一排輸入框隱藏,並將輸入的內容依次填充到第二排的6個輸入框中。

一、如何將兩排輸入框合並?

我們只需要給第一排文本框設置寬高為0就可以了,這樣整個輸入框就被隱藏起來了。然后將第二排的6個文本框設置成不可輸入(disabled)。

看一下標簽文件:

<!--
  輸入驗證碼
-->
<view class="insert-code">
  <view>
    <view class="insert-title">請輸入驗證碼</view>
    <view class="insert-tips">驗證碼已發送至{{phoneNum}}</view>
  </view>
  <view>
    <view class="v-code flex-content">
        <block wx:for="{{6}}" wx:key="item">
            <input data-code="v" type="number" disabled catchtap="tapFn"></input>
        </block>
    </view>
    <input type="number" class="ipt" maxlength="6" focus="{{isVFocus}}" bindinput="showVCode"></input>
</view>

再看一下css文件:

.insert-code{
  padding: 48rpx;
}
.v-code{
  margin-top: 100rpx;
}
.insert-title{
  font-size: 36rpx;
  color: #000000;
  font-weight: bold;
}
.insert-tips{
  font-size: 24rpx;
  color: #959191;
  margin-top: 20rpx;
}
.v-code input{
  width: 75rpx;
  height: 72rpx;
  margin-right: 30rpx;
  padding-bottom: 8rpx;
  border: 2rpx solid #cccccd;
  text-align: center;
  color: #333333;
  font-size: 38rpx;
  border-radius: 10rpx;
}
.flex-content{
  display: flex;
  align-items: center;
}
.is-input{
  border-color: #079aff !important;
}
.ipt{
  height: 0;
  width: 0;
}
.c-blue{
  color: #079aff;
}
.again-tip{
  font-size: 28rpx;
  color: #959191;
}
.next-btn{
  margin-top: 80rpx;
}

二、如何將輸入的內容顯示出來

給隱藏的輸入框添加監聽輸入事件(bindinput),將輸入的字符循環遍歷到第二排文本框中,這樣我們就可以每輸入一個字符,然后就渲染到6個文本框中相應的位置。

<!--
  輸入驗證碼
-->
<view class="insert-code">
  <view>
    <view class="insert-title">請輸入驗證碼</view>
    <view class="insert-tips">驗證碼已發送至{{phoneNum}}</view>
  </view>
  <view>
    <view class="v-code flex-content">
        <block wx:for="{{6}}" wx:key="item">
            <input data-code="v" class="{{vCodeValue.length === index && isVFocus ? 'is-input' : ''}}" type="number" value="{{vCodeValue.length>=index+1 ? vCodeValue[index] : ''}}" disabled catchtap="tapFn"></input>
        </block>
    </view>
    <input type="number" class="ipt" maxlength="6" focus="{{isVFocus}}" bindinput="showVCode"></input>
</view>

在JS代碼中的監聽事件:

import request from '../../utils/http';
import utils from '../../utils/utils';
// pages/forget-psd/insert-code.js
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    vCodeValue: '',
    isVFocus: true,
    phoneNum: '',//手機號碼
  },
  showVCode: function(e){
    const that = this;
    that.setData({
      vCodeValue: e.detail.value,
    });
  },
  tapFn(e){
    const that = this;
    that.setData({
      isVFocus: true,
    });
  },
  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {
    
  },
  
})

好了,這期內容先講到這里。下期再見!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM