vue輸入框中輸完后光標自動跳到下一個輸入框中的實現(xiàn)方法
前言
最近接到這么一個需求,做一個安全碼的輸入框,限制為6位數(shù),但是每一個寫入的值都是一個輸入框,共計6個輸入框,當前輸入框?qū)懭胫岛螅鈽俗詣犹较乱粋€輸入框中,刪除當前輸入框?qū)懭氲闹岛笤僮詣犹缴弦粋€輸入框中。
實現(xiàn)思路
首先我們需要通過 keyup()
事件在用戶輸入完字符后,利用 document.getElementsByClassName
方法獲取到輸入框的 dom
元素集合,拿到當前元素的 key
和 index
值,通過判斷確定光標是否跳到下一個輸入框(focus
)還是光標失焦(blur
);keydown()
事件主要就是為了防止一旦輸入過快,一個輸入框中會有多個字符的問題。 本章用到的屬性以及方法如下:
focus()
focus()
當元素獲得焦點時(當通過鼠標點擊選中元素或通過 tab
鍵定位到元素時),發(fā)生 focus
事件。focus()
方法觸發(fā) focus
事件,或規(guī)定當發(fā)生 focus
事件時運行的函數(shù)。
blur()
當元素失去焦點時發(fā)生 blur
事件。blur()
方法觸發(fā) blur
事件,或規(guī)定當發(fā)生 blur
事件時運行的函數(shù)。
keyup()
keyup()
方法觸發(fā) keyup
事件,或規(guī)定當發(fā)生 keyup
事件時運行的函數(shù)。
keydown()
當鍵盤鍵被按下時觸發(fā) keydown
事件。需要注意的是 keydown()
是在鍵盤按下觸發(fā),而 keyup()
是在鍵盤松手就會觸發(fā)。
document.getElementsByClassName()
getElementsByClassName()
方法返回文檔中所有指定類名的元素集合,作為 NodeList
對象。NodeList
對象代表一個有順序的節(jié)點列表。NodeList
對象 我們可通過節(jié)點列表中的節(jié)點索引號來訪問列表中的節(jié)點(索引號由0開始)。
完整源碼
<template> <div class="parentBox"> <div v-for="(item, index) in inputList" :key="index"> <input type="text" v-model="item.pinless" class="inputValue" @keyup="keyboard($event, index)" @keydown="expurgate(index)" /> </div> </div> </template> <script> export default { data() { return { // 輸入框循環(huán)的數(shù)組 inputList: [ { pinless: "" }, { pinless: "" }, { pinless: "" }, { pinless: "" }, { pinless: "" }, { pinless: "" }, ], }; }, methods: { // 鍵盤松開事件 keyboard(e, index) { let domNode = document.getElementsByClassName("inputValue"), currInput = domNode[index], nextInput = domNode[index + 1], lastInput = domNode[index - 1]; if (e.keyCode != 8) { if (index < this.inputList.length - 1) { nextInput.focus(); } else { currInput.blur(); } } else { if (index != 0) { lastInput.focus(); } } }, // 鍵盤按下觸發(fā) expurgate(index) { this.inputList[index].pinless = ""; }, }, }; </script> <style scoped> .parentBox { padding: 20px; display: flex; } .parentBox div:nth-child(n + 2) { margin-left: 4px; } input { color: #606266; font-size: 18px; text-align: center; width: 54px; height: 62px; border: 2px solid gainsboro; border-radius: 4px; } </style>
實現(xiàn)效果
總結(jié)
到此這篇關(guān)于vue輸入框中輸完后光標自動跳到下一個輸入框中的實現(xiàn)方法的文章就介紹到這了,更多相關(guān)vue輸入框輸完自動跳到下個內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談Vue3 Composition API如何替換Vue Mixins
這篇文章主要介紹了淺談Vue3 Composition API如何替換Vue Mixins,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04vue2 中如何實現(xiàn)動態(tài)表單增刪改查實例
本篇文章主要介紹了vue2 中如何實現(xiàn)動態(tài)表單增刪改查實例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06