原生微信小程序,实现方格验证码输入框

2023-12-13 05:53:46

WXML

<view class="input_box">
			<block wx:for="{{carNumerArr}}" wx:key="index" wx:for-index="index">
				<input class="grid-input" type="number" maxlength="1" bindinput="handleInput" data-index="{{index}}" focus="{{item.focus}}" value="{{item.value}}" />
				</block>
		</view>

JS

  data: {
        carNumerArr: [
            { value: "", focus: false, },
            { value: "", focus: false, },
            { value: "", focus: false, },
            { value: "", focus: false, },
            { value: "", focus: false, },
            { value: "", focus: false, },
        ],
        verificationCode:"",
    },
    handleInput(e) {
        const that = this
        const index = e.currentTarget.dataset.index //下标
        const value = e.detail.value //值
        let carNumerArr = that.data.carNumerArr
        carNumerArr[index].value = value;
        if (value) {
            for (let i = 0; i < carNumerArr.length; i++) {
                carNumerArr[i].focus = false
            }
            if (index == carNumerArr.length - 1) {
                carNumerArr[index].focus = true
            } else {
                carNumerArr[index + 1].focus = true
            }
        } else {
            console.log('删除')
            carNumerArr[index].value = ''
            for (let i = 0; i < carNumerArr.length; i++) {
                carNumerArr[i].focus = false
            }
            if (index !== 0) {
                carNumerArr[index - 1].focus = true
            } else {
                carNumerArr[0].focus = true
            }
        }
        that.setData({
            carNumerArr: carNumerArr
        })
        let verCode = []
        for(let i =0;i < that.data.carNumerArr.length;i++){
            verCode[i] = that.data.carNumerArr[i].value
        }
        console.log(verCode)
        const str = verCode.join('');
        console.log(str)
        that.setData({
            verificationCode:str
        })
    },

文章来源:https://blog.csdn.net/W8034/article/details/134947662
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。