vue3中的回车键完成input的切换功能

文章讲述了如何在多个输入框(由Vue.js的v-for动态渲染)中,通过监听键盘事件,当用户按下回车键时,利用nextElementSibling属性将焦点切换到下一个输入框。这种方法适用于同一层元素结构中。

目前我完成的好像是在不同的div中是实现不了的,因为我使用了nextElementSibling这个属性,如果你们有更好的全局实现的方法,不妨留在评论。

 <div class="data">
        <input
          class="input"
          placeholder="输入xxx"
        />
        <input
          v-for="i in arr"
          :key="i"
          class="input"
          :placeholder="i"
        />
</div>
.input {
  flex-wrap: wrap;
  margin-bottom: 0.5rem;
  width: 15rem;
  height: 2rem;
}

const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

// 监听键盘事件 如果按键是回车键就执行函数 handleKeyup
document.onkeydown = function (e) {
  if (e.key === 'Enter') {
    handleKeyup(e.key)
  }
}
const handleKeyup = (e) => {
  if (e === 'Enter') {
    // activeElement属性获取当前获得焦点的元素
    const activeInput = document.activeElement
    // console.log(activeInput)
    // nextSibling 属性返回元素节点之后的兄弟节点(包括文本节点、注释节点);
    // nextElementSibling属性返回指定元素之后的下一个兄弟元素(相同节点树层中的下一个元素节点)(不包括文本节点、注释节点)
    let nextInput = activeInput.nextElementSibling
    // console.log(nextInput)
    nextInput && nextInput.focus()
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值