多个input输入完成自动切换到下一个输入框
发布于 3 年前 作者 ming45 931 次浏览 来自 分享
  • 需求:
    一个input输入完回车,切换到下一个input。
  • 思路:
    JS里声明2个变量: focus是否获得焦点,focusIndex需要焦点的序号。wxml中给input设置id,设置focus属性由这两个变量来控制。在JS的输入完成监听事件里获取下一个input的id序号并修改变量。

js:

Page({
  /**
   * 页面的初始数据
   */
  data: {
    ...
    // 是否获取焦点
    focus: false,
    // 需要获取焦点的序号
    focusIndex: 0
  },
  // 输入完成事件
  confirmListener (event) {
    let currentIndex = event.currentTarget.dataset.categoryIndex
    if (currentIndex < input的数量 - 1) {
      this.setData({
        focus: true,
        focusIndex: currentIndex + 1
      })
    }else {
      this.setData({
        focus: false
      })
    }
  },
  // 输入时事件
  inputListener(event) {
    ...
    let currentIndex = event.currentTarget.dataset.categoryIndex
    if (this.focusIndex != currentIndex) {
      this.setData({
        focusIndex: currentIndex
      })
    }
  },
})

wxml:

<input id="input{{index}}" data-category-index="{{index}}"  
bindinput="inputListener" bindconfirm="confirmListener"  
focus="{{focus && focusIndex == index}}"
1 回复

感谢分享

在写表单时非常有用

回到顶部