簡體   English   中英

Go 到 maxLength 的下一個輸入字段?

[英]Go to next input field at maxLength?

我在 Vue 中有一個表單,它有一些組合輸入,用於電話號碼輸入的樣式原因。

我的問題是用戶必須點擊標簽才能將 go 轉到電話號碼的下一個輸入字段。

有沒有辦法檢查電流和輸入的最大長度以及何時滿足 go 到下一個輸入?

<div class="combined-input combined-input--phone" :class="{'error--input': phoneInvalid('patientInformation')}">
  <div class="open-parenthesis"></div>

  <input type="text" id="phoneArea" maxlength="3" @blur="$v.formData.patientInformation.phone.$touch()" v-model.trim="$v.formData.patientInformation.phone.area.$model">

  <div class="close-parenthesis"></div>

  <input type="text" id="phoneA" maxlength="3" @blur="$v.formData.patientInformation.phone.$touch()" v-model.trim="$v.formData.patientInformation.phone.a.$model">

  <div class="dash"></div>

  <input type="text" id="phoneB" maxlength="4" @blur="$v.formData.patientInformation.phone.$touch()" v-model.trim="$v.formData.patientInformation.phone.b.$model">
</div>

可以肯定的是,不建議在 UX 方面這樣做,但這里有一個關於如何實現它的示例: https://codesandbox.io/s/move-to-next-input-on-condition-103b5?file=/src/應用程序.vue

有用代碼的主要部分是

focusNextOncePopulated(event, max) {
  if (event.target.value.length === max) {
    const nextElement = this.$refs?.[`input-${Number(event.target.dataset.index) +1}`]
    if (nextElement) nextElement.focus()
  }
},

說明:每次輸入字符時,檢查字段的長度是否達到您在特定輸入上設置的最大值。 如果是,並且有與兄弟相似的輸入,則將其聚焦。
在性能方面,添加幾毫秒的debounce也會很好。

編輯:為了防止嘗試在 DOM 中找到正確的下一個input的任何問題,我們在每個輸入上設置了一些參考(在 Vue 中推薦的方式為 select 一些 DOM 元素)。 然后,當我們達到max時,我們將當前的輸入data-index加一,這使我們能夠將 go 到下一個輸入。

PS: ?. 語法是可選鏈接,它可以防止丑陋的代碼,並允許在達到max后如果沒有下一個input則避免錯誤。

PS:不確定是否有辦法直接在它的@input事件上獲取元素的$refs ,但如果有,我不知道該怎么做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM