小程序输入框完成切换到下个输入框
需求:页面有多个输入框,一个输完点击回车,切换到下个输入框
思路:利用小程序输入框的focus(获取焦点)属性,在bindconfirm事件(点击完成后触发)里设置变量,来控制输入框聚焦位置。
1、wxml
<input data-index="{{index}}" bindinput="inputListener"
bindconfirm="confirmListener" focus="{{focus && focusIndex == index}}"
2、js
Page({
/**
* 页面的初始数据
*/
data: {
// 是否获取焦点
focus: false,
// 需要获取焦点的序号
focusIndex: 0
},
// 输入完成事件
confirmListener (event) {
let currentIndex = event.currentTarget.dataset.index
if (currentIndex < input的数量 - 1) {
this.setData({
focus: true,
focusIndex: currentIndex + 1
})
}else {
this.setData({
focus: false
})
}
},
// 输入时事件
inputListener(event) {
let currentIndex = event.currentTarget.dataset.index
if (this.focusIndex != currentIndex) {
this.setData({
focusIndex: currentIndex
})
}
},
})